Ejemplo n.º 1
0
    def post(self, request):
        print('*' * 50)
        data = request.data
        print(data)

        serializer = TodoValidator(data=data)
        try:
            serializer.is_valid(raise_exception=True)
        except ValidationError as r:
            print(r)
            return JsonResponse({
                "messages": [
                    {"text": "I need you to enter Title, Description and DataTime in format (dd/mm/yy 23:50)"},
                ]
            })

        validated_data = serializer.data
        print(validated_data)
        # print(data['hello'])
        print('*' * 50)
        u_id = data['messenger user id']
        user = models.User.objects.get(messenger_id=u_id)
        new_rec = Todo(title=validated_data['title'], image_url=validated_data['image_url'],
                       subtitle=validated_data['subtitle'],date_time=validated_data['date_time'],reporter = user)
        new_rec.save()
        return JsonResponse({
                "messages": [
                    {"text": "You have successfully added a new task, let's check the list now"},
                ]
            })
Ejemplo n.º 2
0
def create(request):
    title = request.POST.get('title')
    deadline = request.POST.get('deadline')
    todo = Todo(title=title, deadline=deadline)
    todo.save()

    return redirect('/todos/')
Ejemplo n.º 3
0
def ajax(request):
	# no one is logged in
	if request.user.is_authenticated() == False:
		return HttpResponse('You must be logged in <a href="accounts/login">log in</a>')

	# delete a todo
	if request.GET.has_key('delete_id'):
		Todo.objects.get(id=request.GET.get('delete_id')).delete()
		
	# change the status of a todo
	if request.GET.has_key('change_status'):
		item = Todo.objects.get(id=request.GET.get('change_status'))
		item.done = True
		item.save()
	
	# post a new todo
	if request.GET.has_key('title') and request.GET.has_key('description'):
		new_item = Todo(title=request.GET.get('title'), description=request.GET.get('description'), done=False, user=request.user)
		new_item.save()

	# render todo list
	todo_list = Todo.objects.filter(user=request.user.id).order_by('done')

	t = loader.get_template('list.html')
	c = Context({
		'todo_list': todo_list
	})

	return HttpResponse(t.render(c))
Ejemplo n.º 4
0
def create(request):
    title = request.POST.get('title')
    deadline = request.POST.get('deadline')
    todo = Todo(title=title, deadline=deadline)    
    todo.save()   # db.session.add() + db.session.commit()과 동일    
    
    return redirect('/todos/')
Ejemplo n.º 5
0
 def test_description_is_greater_than_0(self):
     """
     Check if the size of the string is more than 1
     Return true if it meets the size requirements
     """
     description_string = Todo(description="Checking the size")
     self.assertEqual(description_string.description_is_more_than_0(), True)
Ejemplo n.º 6
0
def create(request):
    if request.method == 'POST':
        form = TodoForm(request.POST)
        if form.is_valid():
            todo = Todo(todo=form.cleaned_data['todo'])
            todo.save()
            return HttpResponseRedirect('/')
Ejemplo n.º 7
0
class TransactionTest2(TransactionTestCase):

    def setUp(self):
        self.client = Client()
        self.todo = Todo()
        self.todo.activity = "hola"
        self.todo.save()

    def test_edit_view(self):
        response = self.client.get(reverse("edit", kwargs={"pk":self.todo.pk}))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,"add.html")

    def test_edit(self):
        response = self.client.post(reverse("edit",kwargs={"pk":self.todo.pk}),
                                    {"activity":"actividad"},
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,"index.html")
        self.assertEqual(response.context['list'].count(),1)
        self.assertEqual(Todo.objects.get(pk=self.todo.pk).activity, "actividad")

    def test_view_delete(self):
        response = self.client.post(reverse("delete",kwargs={"pk":self.todo.pk}),
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,"index.html")
        self.assertEqual(response.context['list'].count(),0)
Ejemplo n.º 8
0
def main(request):
    if request.method == "POST":
        topic = request.POST["topic"]
        content = request.POST["content"]
        p = Todo(topic=topic, content=content)
        p.save()
    return render(request, 'todo/index.html')
Ejemplo n.º 9
0
def edit(request):
    """编辑 todo 视图函数"""
    # 处理 POST 请求
    if request.method == 'POST':
        form = request.form
        print(f'form: {form}')

        id = int(form.get('id', -1))
        content = form.get('content')

        if id != -1 and content:
            todo = Todo.get(id)
            if todo:
                todo.content = content
                todo.save()
        return redirect('/index')

    # 处理 GET 请求
    args = request.args
    print(f'args: {args}')

    id = int(args.get('id', -1))
    if id == -1:
        return redirect('/index')

    todo = Todo.get(id)
    if not todo:
        return redirect('/index')

    context = {
        'todo': todo,
    }
    return render_template('edit.html', **context)
Ejemplo n.º 10
0
def addTodo(request):
    form = TodoForm(request.POST)

    if form.is_valid():
        new_todo = Todo(text=request.POST['text'])
        new_todo.save()
    return redirect('index')
Ejemplo n.º 11
0
class TodoTest(TestCase):
    def setUp(self):
        self.todo = Todo(description='Do anything')
        self.todo.save()

    def test_create(self):
        'Todo may be saved'
        self.assertEqual(1, self.todo.pk)

    def test_str(self):
        'Todo string representation may be the description.'
        self.assertEqual('Do anything', str(self.todo))

    def test_order(self):
        'Todos may be ordered by order field'
        todo_2 = Todo(description='Do other thing')
        todo_2.save()
        self.assertEqual(1, self.todo.order)
        self.assertEqual(2, todo_2.order)

    def test_done(self):
        'Todo done may be unchecked'
        self.assertEqual(False, self.todo.done)
        self.todo.done = True
        self.assertEqual(True, self.todo.done)
Ejemplo n.º 12
0
def add(request):
    title = request.POST['title']
    t = Todo(title=title, completed=False)
    print('todo add 1 <{}> <{}> <{}>'.format(t.__dict__, title, request.POST))
    t.save()
    print('todo add 2 <{}>'.format(t.__dict__))
    return redirect('todo_index_all')
Ejemplo n.º 13
0
 def test_create_todos(self):
     ''' test the creation of todos '''
     self.create_todos()
     self.assertEqual(Todo.select().count(), 2)
     self.assertEqual(
         Todo.select().get().name,
         'Walk Dog'
     )
Ejemplo n.º 14
0
def addTodo(request):
    if request.method == "GET":
        return redirect("/")
    else:
        title = request.POST.get("title")
        newTodo = Todo(title=title, completed=False)

        newTodo.save()
        return redirect("/")
Ejemplo n.º 15
0
def deleteTodo(request, pk):
    todo = Todo.objects.get(pk=pk)
    if todo.user == request.user:
        Todo.delete(todo)
        messages.success(request, "to do delete successfully")
        return HttpResponseRedirect('/')
    else:
        messages.error(request, "you are not authorized to delete this to do")
        return HttpResponseRedirect('/')
Ejemplo n.º 16
0
def post_todo(request):
    user = request.user
    if user.is_authenticated():    
        name = request.POST.get('author')
        text = request.POST.get('body')
        color = request.POST.get('color')      
        todo = Todo(user=user,name=name,text=text,color=color,x=156,y=138,z=100)
        todo.save()      
        return HttpResponse('29')      
Ejemplo n.º 17
0
def insert_todo(payload, user):
    new_todo = Todo(
        tasks=payload["tasks"],
        period=payload['time_for_accomplishing'],
        time_of_accomplishing=payload['time_of_accomplishing'],
        reporter=user,
    )
    new_todo.save()
    serialized = TodoSerializer(new_todo)
    return serialized.data
Ejemplo n.º 18
0
def new(request):
    """新建 todo 视图函数"""
    form = request.form
    print(f'form: {form}')

    content = form.get('content')
    if content:
        todo = Todo(content=content)
        todo.save()
    return redirect('/index')
Ejemplo n.º 19
0
 def test_get_single_todo(self):
     TodoModelTestCase.create_todos()
     user = User.select().get()
     headers = UserModelTestCase.get_headers(user)
     
     response = self.app.get('/api/v1/todos/'
                             + str(Todo.select().get().id),
                             headers=headers)
     self.assertEqual(response.status_code, 200) 
     self.assertEqual(Todo.select().get().name, 'Walk Dog')
Ejemplo n.º 20
0
 def post(self,request):
     serializer = TodoSerializer(data = request.DATA)
     if not serializer.is_valid():
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
     else:
        data = serializer.data
        owner = request.user
        t = Todo(owner=request.user, description=data['description'],done=False)
        t.save()
        request.DATA['id'] = t.pk;
        return Response(request.DATA,status=status.HTTP_201_CREATED)
Ejemplo n.º 21
0
def add_todo(request):
    todo_text = request.POST.get('todo_text', None)
    logged_in_user = request.user
    if Todo.objects.filter(text=todo_text, user=logged_in_user).count() != 0:
        messages.error(
            request,
            'A todo with this text already exists. Try some other text.')
    else:
        new_todo = Todo(text=todo_text, user=logged_in_user)
        new_todo.save()
    return redirect('todo:index_view')
Ejemplo n.º 22
0
def add(request):
    if (request.method == 'POST'):
        title = request.POST['title']
        description = request.POST['description']

        todo = Todo(title=title, description=description)
        todo.save()

        return redirect('/todo/')
    else:
        return render(request, 'add.html')
Ejemplo n.º 23
0
 def put(self,request,todo_id):
     serializer = TodoSerializer(data=request.DATA)
     if not serializer.is_valid():
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
     else:
        data = serializer.data
        desc = data['description']
        done = data['done']
        t = Todo(id=todo_id,owner=request.user,description=desc,done=done,updated=datetime.now())
        t.save()
        return Response(status=status.HTTP_200_OK)
Ejemplo n.º 24
0
 def post(self, request):
     serializer = TodoSerializer(data=request.DATA)
     if not serializer.is_valid():
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     else:
         data = serializer.data
         owner = request.user
         t = Todo(owner=owner, description=data['description'], done=False)
         t.save()
         request.DATA['id'] = t.pk  # return id
         return Response(request.DATA, status=status.HTTP_201_CREATED)
Ejemplo n.º 25
0
def index(request):
   task = Todo.objects.all()
   context = {'task' : task}
   if request.POST.get('todos')=="":
      messages.error(request,"Please , Add todo.....")
      return  render(request , 'index.html' , context);
   else:
      if request.method =='POST': 
         t1 = request.POST.get('todos')
         t1 = Todo(new_task = t1)
         t1.save()
         messages.success(request, 'Todo Added')
   return  render(request , 'index.html' , context);
Ejemplo n.º 26
0
 def put(self, request, todo_id):
     serializer = TodoSerializer(data=request.DATA)
     if not serializer.is_valid():
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     else:
         data = serializer.data
         desc = data['description']
         done = data['done']
         t = Todo(id=todo_id, owner=request.user, description=desc,\
                  done=done, updated=datetime.now())
         t.save()
         return Response(status=status.HTTP_200_OK)
Ejemplo n.º 27
0
    def test_delete_todo(self):
        TodoModelTestCase.create_todos()
        user = User.select().get()
        headers = UserModelTestCase.get_headers(user)
        
        response = self.app.delete('/api/v1/todos/' + 
                                    str(Todo.select().get().id), 
                                    headers=headers)

        self.assertEqual(response.status_code, 204) 
        self.assertNotEqual(Todo.select().get().name, 'Walk Dog')
        self.assertEqual(response.location, 
                        'http://localhost/api/v1/todos')    
Ejemplo n.º 28
0
def todo(request):
    if request.method == 'GET':
        todo_all_list = [todo for todo in Todo.objects.all().values()]
        return JsonResponse(todo_all_list, safe=False)
    elif request.method == 'POST':
        req_data = json.loads(request.body.decode())
        content = req_data['content']
        done = req_data['done']
        todo = Todo(content = content, done=done)
        todo.save()
        return HttpResponse(status=201)
    else:
        return HttpResponseNotAllowed(['GET', 'POST'])    
Ejemplo n.º 29
0
def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            not_completed_todo = Todo(
                text='Not completed todo example (click me to mark as done)',
                user_id=User.objects.filter(username=username).first())
            completed_todo = Todo(
                text=
                'completed todo example (click me to mark as not completed)',
                complete=True,
                user_id=User.objects.filter(username=username).first())
            completed_todo.save()
            not_completed_todo.save()
            messages.success(request, f'Account created for {username}!')

            return redirect('login')
    else:
        form = UserRegisterForm()
    context = {
        'form': form,
    }
    return render(request, 'users/register.html', context)
Ejemplo n.º 30
0
 def test_put_todo(self):
     TodoModelTestCase.create_todos()
     user = User.select().get()
     headers = UserModelTestCase.get_headers(user)
     
     todo_data = {'name': 'Feed Dog'}
     
     response = self.app.put('/api/v1/todos/' 
                             + str(Todo.select().get().id), 
                             data=todo_data, headers=headers)
     self.assertEqual(response.status_code, 200) 
     self.assertEqual(Todo.select().get().name, 'Feed Dog')
     self.assertEqual(response.location, 
                     'http://localhost/api/v1/todos/1') 
Ejemplo n.º 31
0
def index(request):
    if request.method =='POST':

        new_todo= request.POST['todo']
        if not new_todo or len(new_todo) <3:
            return redirect('index')
        todo = Todo()

        todo.todo=new_todo
        todo.save()
        return redirect('index')
    todos=Todo.objects.all()
    print(todos)
    return render(request,'inedx.html',{'todos':todos})
Ejemplo n.º 32
0
def addTodo(request):
	print ('addtodo')
	if request.method == 'POST':			
			todo = request.POST['Item']
			print (todo)
			if todo:
				todolist = Todo()
				todolist.todo=todo
				todolist.pubtime=datetime.datetime.today()
				todolist.save()
	todos = Todo.objects.all()
	return render_to_response('todolist.html',{
                'todos':todos,       
                },context_instance=RequestContext(request))
Ejemplo n.º 33
0
def addItem(request):
    t = Todo()
    t.text = request.POST.get('todo_text', '')
    t.save()
    
    if request.method == 'POST':
        form = TodoForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
        #Item.objects.create(text=request.POST['item_text'])
        #return redirect('/')

    else:
        return render(request, 'todo/create.html', {'form': form})
Ejemplo n.º 34
0
def ManageAddView(request, username=''):

    user = User.objects.get(username=username)
    form = TodoForm(request.POST or None)
    if form.is_valid():
        thisTodo = form.cleaned_data['todo']
        thisPriority = form.cleaned_data['priority']
        thisUser = User.objects.get(username=username)

        todo = Todo(user=thisUser, todo=thisTodo, priority=thisPriority, status=1)
        todo.save()

        return HttpResponseRedirect(URL_TODO_MANAGE(user.username))

    return HttpResponseRedirect(URL_TODO_MANAGE(user.username))
Ejemplo n.º 35
0
 def test_all_update_completed(self):
     Todo.create(title='test title').save()
     Todo.create(title='test title').save()
     Todo.create(title='test title').save()
     Todo.all_update_completed(True)
     self.assertEqual(
         Todo.objects.all().filter(completed=True).count(),
         Todo.objects.all().count())
Ejemplo n.º 36
0
def addTodo_page():
    form = TodoForm()
    id = current_user.id
    #request.args.get("user")
    if request.args.get("action") == 'add':
        if form.validate_on_submit():
            print('form executed')

            todo_to_create = Todo(name=form.name.data,
                                  category=form.category.data,
                                  owner=id)
            db.session.add(todo_to_create)
            db.session.commit()
            print('db executed')
            return redirect(url_for('dashboard_page', page_num=1))
    if form.errors != {}:
        for err_msg in form.errors.values():
            flash(err_msg)
    if request.args.get("action") == "edit":
        idTodo = request.args.get("todo")
        todo = Todo.query.filter_by(id=idTodo).first()
        if form.validate_on_submit():
            todo.name = form.name.data
            todo.category = form.category.data
            db.session.commit()
            return redirect(url_for('dashboard_page'))
        return render_template('addTodo.html',
                               form=form,
                               todo=todo,
                               action='edit')

    return render_template('addTodo.html', form=form)
Ejemplo n.º 37
0
def index(request):

    if request.method == 'GET':
        todos = Todo.objects.all()
        return render(request, 'index.html', {'todos': todos})

    if request.method == 'POST':
        todo = request.POST['todo']

        if not todo or len(todo) < 3:
            return "Invalid Todo"

        new_todo = Todo()
        new_todo.todo = todo
        new_todo.save()
        return redirect('index')
Ejemplo n.º 38
0
def index():
    """首页视图函数"""
    # 倒序排序,最近添加的 todo 排在前面
    todo_list = Todo.all(sort=True, reverse=True)
    context = {
        'todo_list': todo_list,
    }
    return render_template('index.html', **context)
Ejemplo n.º 39
0
def update_text(request):   
    user = request.user
    if user.is_authenticated():
        post = request.POST.copy() 
        todo = Todo.get_by_id(int(request.POST.get('id')))
        todo.text = post['value'] 
        todo.put()
        return render_to_response(request, 'todo_changed.html', {'todo': todo})
    else:
        return HttpResponseRedirect('/todo/')
Ejemplo n.º 40
0
def AddView(request):

    if request.method == "POST":
        thisTodo = request.POST['todo']
        thisPriority = request.POST['priority']
        thisUser = User.objects.get(id=1)
        todo = Todo(user=thisUser, todo=thisTodo, priority=thisPriority, flag=1)
        todo.save()

        todolist = Todo.objects.filter(flag=1)
        finishedlist = Todo.objects.filter(flag=0)
        template_name = 'todo/todo.html'
        template_value = {'todolist': todolist, 'finishedlist': finishedlist}
        return render_to_response(template_name, template_value, context_instance=RequestContext(request))
    
    else:
        todo = ''
        template_name = 'todo/add.html'
        template_value = {'todo': todo}
        return render_to_response(template_name, template_value, context_instance=RequestContext(request))
Ejemplo n.º 41
0
def update_position_todo(request):   
    user = request.user
    if user.is_authenticated():
      try:
        todo = Todo.get_by_id(int(request.GET.get('id')))
        todo.x =  int(request.GET.get('x'))
        todo.y =  int(request.GET.get('y'))
        todo.z =  int(request.GET.get('z'))
        todo.put()
        return HttpResponseRedirect('/todo/')
      except KeyError:
        pass
    else:
        return HttpResponseRedirect('/todo/')
Ejemplo n.º 42
0
def add(request):
    page_title="Add"
    hours=[i+1 for i in range(-1,24)]
    minutes=[i+1 for i in range(-1,59)]

    if request.method=="POST":
        form=TodoAddForm(request.POST)
        if form.is_valid():
            todo=Todo(
                todo_name=form.cleaned_data['todo_name'],
                todo_text=form.cleaned_data['todo_text'],
                todo_ttl=form.cleaned_data['todo_date']+" "+request.POST.get('todo_hour')+":"+request.POST.get('todo_min')+':00',
                todo_status=0,
                user_id=request.user.id
            )

            todo.save()
            messages.add_message(request, messages.SUCCESS, u'Tâche ajoutée',extra_tags="alert alert-info")
            return redirect('todo.views.add')

    else:
        form=TodoAddForm()

    return render(request,'todo/add.html',locals())
Ejemplo n.º 43
0
def test_creating_todo_list(app):
    """/api/v1/todos should return the data we have created"""

    t1 = Todo("Test1")
    t1.save()
    t2 = Todo("Test2")
    t2.save()

    resp = app.client.get("/api/v1/todos")
    data = json.loads(resp.data)
    assert len(data['todos']) == 2
Ejemplo n.º 44
0
    def test_get_todos(self):
        # if can get todo
        todo = Todo.create(title='test title')
        todo.save()
        self.assertEqual(todo.id, Todo.get_todos(todo.id).id)
        # if can not get any todos 11111 is dummyid which dose not exist
        self.assertEqual(None, Todo.get_todos(11111))
        Todo.delete()

        # get all todos
        Todo.create(title='test title').save()
        Todo.create(title='test title').save()
        Todo.create(title='test title').save()
        todos = Todo.get_todos()
        self.assertEqual(Todo.objects.all().count(), todos.count())
Ejemplo n.º 45
0
def addTask (request, taskFromJson):
	t = Todo()
	t.task = taskFromJson
	t.save()
	return getTasks(request)
Ejemplo n.º 46
0
    def test_is_all_completed(self):
        Todo.create(title='test title').save()
        Todo.create(title='test title', completed=True).save()
        Todo.create(title='test title').save()
        self.assertFalse(Todo.is_all_completed())

        Todo.all_update_completed(True)
        self.assertTrue(Todo.is_all_completed())

        Todo.delete()
Ejemplo n.º 47
0
def add(request):
    todo = Todo()
    todo.task = request.POST.get('new_task', 'default')
    todo.user = request.user
    todo.save()
    return HttpResponseRedirect(reverse('index'))
Ejemplo n.º 48
0
 def get(self, id):
     todo = Todo.objects(id=id).first()
     todo.completed = not todo.completed
     todo.save()
     return todo_as_dict(todo)
Ejemplo n.º 49
0
 def post(self):
     args = parser.parse_args()
     todo = Todo(args["task"])
     todo.save()
     return todo_as_dict(todo)
Ejemplo n.º 50
0
 def get_context_data(self, request):
     todos = Todo.objects.all().order_by('id')
     return {'todos': todos, 'filter': request.GET.get('filter', ''), 'all_completed': Todo.is_all_completed()}
Ejemplo n.º 51
0
 def _delete(self, todo_ids):
     todos = Todo.get_todos(todo_ids)
     if todos:
         todos.delete()
Ejemplo n.º 52
0
 def _toggle_all_completed(self, toggle_all):
     toggle_all = json.loads(toggle_all)
     Todo.all_update_completed(toggle_all)
Ejemplo n.º 53
0
 def get(self, id):
     return todo_as_dict(Todo.objects(id=id).first())
Ejemplo n.º 54
0
 def get(self):
     resp = {'todos': []}
     for todo in Todo.objects():
         resp['todos'].append(todo_as_dict(todo))
     return resp
Ejemplo n.º 55
0
 def setUp(self):
     self.client = Client()
     self.todo = Todo()
     self.todo.activity = "hola"
     self.todo.save()
Ejemplo n.º 56
0
 def test_models_str_2(self):
     todo = Todo()
     todo.activity = "hola"
     todo.save()
     self.assertEqual(str(todo),"{} {}".format(str(todo.pk), "hola"))
Ejemplo n.º 57
0
    def test_delete(self):
        # delete a todo
        todo = Todo.create(title='test title')
        todo.save()
        Todo.delete(str(todo.id))
        self.assertEqual(
            Todo.objects.all().count(),
            0)

        # delete all todos
        Todo.create(title='test title').save()
        Todo.create(title='test title').save()
        Todo.create(title='test title').save()
        Todo.delete()
        self.assertEqual(
            Todo.objects.all().count(),
            0)
Ejemplo n.º 58
0
 def test_task_crud(self):
     user = get_user_model().objects.create()
     task1 = Todo()
     task1.name = 'Sample task'
     task1.user = user
     task1.save()
     self.assertEqual(task1.priority, 0)
     task2 = Todo()
     task2.name = 'Second task'
     task2.user = user
     task2.save()
     self.assertEqual(task2.priority, 1)
     task1.name = 'New task'
     task1.save()
     task1.delete()
     self.assertEqual(Todo.objects.count(), 1)
Ejemplo n.º 59
0
 def _update(self, data):
     todo = Todo.get_todos(data.get('id'))
     data.update({'completed': json.loads(data.get('completed'))})
     form = TodoForm(data, instance=todo)
     if form.is_valid():
         form.save()