def create(request): todo = Todo(title=request.POST['title'], description=request.POST['description'], due_date=timezone.now().date(), user_id=request.user.id) todo.save() return redirect('todos_index')
def add(request): title = request.POST['title'] if title == '': messages.info(request, 'todo title required') else: todo = Todo(title=title) todo.save() return HttpResponseRedirect(reverse('todos:index'))
def post(self,request): form = TodoForm(request.POST) if form.is_valid(): title = form.cleaned_data.get('title') status = form.cleaned_data.get('status') todo = Todo(user=request.user,title=title,status=status) todo.save() return redirect(self.success_url) return render(request,self.template_name,{'title':self.title,'forms':form})
def add(request): if (request.method == 'POST'): title = request.POST['title'] text = request.POST['text'] todo = Todo(title=title, text=text) todo.save() return redirect('/todos') else: return render(request, 'add.html')
class ModelTestCase(TestCase): """Test suite for models""" def setUp(self): self.todo_name = 'Todo 1' self.todo = Todo(name=self.todo_name) def test_model_can_create_todo(self): """Model can create todo""" old_count = Todo.objects.count() self.todo.save() new_count = Todo.objects.count() self.assertNotEqual(old_count, new_count)
def create_todo(username, todo, deadline, priority): response = False try: t = Todo(todo=todo, deadline=deadline, priority=priority, owner=username) t.save() response = True except: print("Error while creating todo") return response
def create(request): if request.method == "POST": # handle the form data todo_string = request.POST['task'] todo = Todo(task=todo_string) todo.save() return redirect('todos:index') elif request.method == "GET": return render(request, 'todos/create.html')
def test_delete_invalid_todo(self): todo1 = Todo(name='todo1', user=self.user) todo1.save() self.assertTrue(Todo.objects.all().count() == 1) request = self.request_factory.delete(reverse('todos:todo-detail', kwargs={'pk': 2}), format='json') force_authenticate(request, user=self.user) view = TodoDetail.as_view() response = view(request, pk=2) response.render() self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertTrue(Todo.objects.all().count() == 1)
def new(): todo = Todo(title=request.form['title'], content=request.form['content'], author=current_user) db.session.add(todo) db.session.commit() flash('Create successfully!', 'success') return redirect(url_for('home'))
def add(request): user_id = request.user.id if not user_id: return HttpResponseRedirect(reverse('login')) if request.method == 'POST': title = request.POST['title'] text = request.POST['text'] column_id = request.POST['column_id'] todo = Todo(title=title, text=text, column_id=column_id, user_id=user_id) todo.save() return redirect('/todos') else: return render(request, 'add.html')
def handle(self, **options): """ Execute the command. """ print(options) fake = Faker() for _ in range(70): email = fake.email() user = User(username=email, first_name=fake.first_name(), last_name=fake.last_name(), email=email, password=make_password('P@ssw0rd')) user.save() for _ in range(35): todo = Todo(name=fake.sentence(), user=user) todo.save()
def create_todo(): data = request.json todo = Todo(title=data.get('title'), description=data.get('description', ''), completed=data.get('completed', False)) db.session.add(todo) db.session.commit() return jsonify(TodoDetailsSerializer(todo).data), 201
def test_invalid_todo(self): todo1 = Todo(name='todo1', user=self.user) todo1.save() update_data = { 'name': 'updatedName', } self.assertEqual(Todo.objects.get(pk=1).name, 'todo1') request = self.request_factory.patch(reverse('todos:todo-detail', kwargs={'pk': 2}), update_data, format='json') force_authenticate(request, user=self.user) view = TodoDetail.as_view() response = view(request, pk=2) response.render() self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(Todo.objects.get(pk=1).name, 'todo1')
def todo_add(request): priority=int(request.POST.get("priority",'')) if priority in [1, 2, 3, 4]: content=request.POST.get("content",'') user = request.user print "user:"******"content:",content,"priority:",priority ret = 0 if user and content: todo = Todo(content=content, owner=user, priority=priority) todo.save() ret = 1 else: ret = 2 response=HttpResponse() response.write(ret) response['Cache-Control'] = 'no-cache' return response else: pass
def todo_list(request, user): if request.method == 'GET': # 获取该用户的所有土豆 todo_all = user.todos.all() # 去除今天之前的土豆 todo_all = [todo for todo in todo_all if not todo.is_past()] # 每页多少todo,默认5个 per_page = request.GET.get('per_page', 5) paginator = Paginator(todo_all, per_page) # 请求页数,默认第一页 page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) data = { 'count': len(page_obj), 'todos': [model_to_dict(page) for page in page_obj] } return my_response(data) if request.method == 'POST': # 添加一个土豆 todo_new = json.loads(request.body) for k, v in todo_new.items(): if k not in Todo.__dict__: return bad_request_400('Todo field error') try: todo = Todo(**todo_new) todo.owner = user todo.save() except Exception as e: return bad_request_400(message='Database error') return my_response('Create success')
def test_get_invalid_single_todo(self): todo1 = Todo(name='todo1', user=self.user) todo1.save() todo2 = Todo(name='todo2', user=self.user) todo2.save() request = self.request_factory.get(reverse('todos:todo-detail', kwargs={'pk': 3}), format='json') force_authenticate(request, user=self.user) view = TodoDetail.as_view() response = view(request, pk=3) response.render() todo = Todo.objects.get(pk=2) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_single_todo(self): todo1 = Todo(name='todo1', user=self.user) todo1.save() todo2 = Todo(name='todo2', user=self.user) todo2.save() request = self.request_factory.get(reverse('todos:todo-detail', kwargs={'pk': 2}), format='json') force_authenticate(request, user=self.user) view = TodoDetail.as_view() response = view(request, pk=2) response.render() todo = Todo.objects.get(pk=2) serializer = TodoSerializer(todo, context={'request': request}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
def test_get_all_todos(self): todo1 = Todo(name='todo1', user=self.user) todo1.save() todo2 = Todo(name='todo2', user=self.user) todo2.save() request = self.request_factory.get(reverse('todos:todo-list'), format='json') force_authenticate(request, user=self.user) view = TodoList.as_view() response = view(request) response.render() todos = Todo.objects.all() serializer = TodoSerializer(todos, many=True, context={'request': request}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
def addTodo(request): #to get the data from post method title = request.POST['title'] desc = request.POST['description'] todo = Todo() todo.title = title todo.description = desc print('>>>>>>>') print(title) print(desc) #to save the data into the postgres todo.save() # return HttpResponseRedirect('') return redirect('/')
def post(self, request, *args, **kwargs): todotext = request.POST['todotext'] obj = Todo(todo_text=todotext) obj.save() context = {'todos': Todo.objects.all()} return render(request, self.template_name, context)
def signup(request): if request.method == "POST": if not request.POST['email'] or not request.POST['username'] or not request.POST['password1']: # Check if email field empty return render(request, 'accounts/signup.html', {'error': 'Cannot leave fields blank'}) if request.POST['password1'] == request.POST['password2']: # Check that email is not already taken try: profile = User.objects.get(email=request.POST['email']) return render(request, 'accounts/signup.html', {'error': 'Email has already been taken'}) except: pass # Check that username is not already taken try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error': 'Username has already been taken'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], email=request.POST['email'], password=request.POST['password1']) login(request, user) # If successful sign up, create a profile profile = Profile() profile.user = request.user profile.save() # Add examples to profile # Example todo todo = Todo() todo.title = "Groceries" todo.pub_date = timezone.now() todo.author = request.user todo.point_value = 10 todo.completed = False todo.save() todo2 = Todo() todo2.title = "Add a new Task!" todo2.pub_date = timezone.now() todo2.author = request.user todo2.point_value = 10 todo2.completed = False todo2.save() todo3 = Todo() todo3.title = "Clean room" todo3.pub_date = timezone.now() todo3.author = request.user todo3.point_value = 10 todo3.completed = False todo3.save() # Example Goals goal = Goal() goal.title = "Study" goal.amount_goal = 10 goal.units = "hours" goal.amount_per_increment = 1 goal.point_value = 25 goal.pub_date = timezone.now() goal.author = request.user goal.current_amount_done = 0 goal.times_completed = 0 goal.save() goal2 = Goal() goal2.title = "Jogging" goal2.amount_goal = 30 goal2.units = "miles" goal2.amount_per_increment = 1 goal2.point_value = 30 goal2.pub_date = timezone.now() goal2.author = request.user goal2.current_amount_done = 0 goal2.times_completed = 0 goal2.save() goal2 = Goal() goal2.title = "Pull-ups" goal2.amount_goal = 100 goal2.units = "reps" goal2.amount_per_increment = 20 goal2.point_value = 15 goal2.pub_date = timezone.now() goal2.author = request.user goal2.current_amount_done = 0 goal2.times_completed = 0 goal2.save() # Example journal entry entry = Entry() entry.title = "Hello world!" entry.content = "Welcome to the Productivity Helper app! This is an example Journal entry, which you are free to edit or delete." entry.author = request.user entry.published_date = timezone.now() entry.save() return redirect('todos:home') else: return render(request, 'accounts/signup.html', {'error': 'Passwords did not match'}) else: return render(request, 'accounts/signup.html')
def save(self, request): """ HTTP POST Method 를 사용하고 save 라는 path 를 사용할 때 데이터를 저장하는 함수 저장하려는 데이터와 실제 DB에 저장된 데이터가 있을 때, 그 차이에 대해서만 저장하고 삭제한다. """ try: jsonDataString = request.POST.get("jsonData") jsonDataList = json.loads(jsonDataString) josnDataDict = {} ## id 를 key 로, 나머지 데이터를 value 로하는 dict index = 2**32 for item in jsonDataList: _id = item["id"] if _id == "": ## 새로 추가 되는 아이템인 경우 id 가 0일 수 있는데, 이 경우 임의의 id를 부여 item["id"] = _id = index index += 1 josnDataDict[_id] = item jsonDataSet = set(josnDataDict.keys()) objects = self.get_queryset().filter(user=request.user) objectsDict = {} ## id 를 key로, 나머지 데이터를 value 로하는 dict for item in objects: _id = item.id objectsDict[_id] = item objectsSet = set(objectsDict.keys()) ## jsonData 와 objects(DB) 를 비교해서 ## jsonData 에만 존재, 데이터 추가 itemToAdd = jsonDataSet - objectsSet for _id in itemToAdd: item = josnDataDict[_id] create_time = datetime.datetime.fromtimestamp( item["create_time"] / 1000) todo = Todo(user=request.user, priority=item["priority"], text=item["text"], done=item["done"], create_time=create_time) todo.save() ## objects에만 존재 데이터 삭제 itemToDelete = objectsSet - jsonDataSet for _id in itemToDelete: item = objectsDict[_id] self.get_queryset().filter(id=_id).delete() ## 양쪽에 다 존재하는 데이터의 done과 priority 상태 확인 itemToUpdateCheck = objectsSet.intersection(jsonDataSet) for _id in itemToUpdateCheck: itemWeb = josnDataDict[_id] itemDB = objectsDict[_id] if itemWeb["done"] != itemDB.done or itemWeb[ "priority"] != itemDB.priority: self.get_queryset().filter(id=_id).update( done=itemWeb["done"], priority=itemWeb["priority"]) result = ErrClass('NOERROR').toDict() return HttpResponse(json.dumps(result), content_type="application/json") except Exception as e: logger.error(traceback.format_exc()) return ErrClass('UNKNWON_ERROR').response()
def test_title(self): todo = Todo(title="first") expected_object_name = todo.title self.assertEqual(expected_object_name, 'first')
def test_description(self): todo = Todo(description="first") expected_obj = todo.description self.assertEqual(expected_obj, 'first')
def add_test_todos(): print('Populating Todo objects...') if not Todo.objects.filter(title='My 1st Todo'): todo = Todo(title='My 1st Todo', text='Reading...') todo.save() if not Todo.objects.filter(title='My 2nd Todo'): todo = Todo(title='My 2nd Todo', text='Playing with my dog...') todo.save() if not Todo.objects.filter(title='My 3rd Todo'): todo = Todo(title='My 3rd Todo', text='Eating...') todo.save() if not Todo.objects.filter(title='My 4th Todo'): todo = Todo(title='My 4th Todo', text='Sleeping...') todo.save() if not Todo.objects.filter(title='My 5th Todo'): todo = Todo(title='My 5th Todo', text='Debugging...') todo.save()
def mutate(cls, root, info, name, id): todo = Todo(name=name) todo.save() return TodoMutation(todo=todo)
def create(self, validated_data): todo = Todo(account=self.context.get('request').user, **validated_data) todo.save() return todo
import datetime import random import sys import faker from api_crud.factory import db from todos.models import Todo fake = faker.Faker() todos_count = db.session.query(Todo.id).count() todos_to_seed = 43 todos_to_seed -= todos_count if todos_to_seed > 0: sys.stdout.write('[+] Seeding %d todos\n' % (todos_to_seed)) start_date = datetime.date(year=2014, month=1, day=1) for i in range(0, todos_to_seed): title = ' '.join(fake.words(nb=random.randint(2, 5))) description = ' '.join(fake.sentences(nb=random.randint(2, 10))) created_at = fake.date_between(start_date=start_date, end_date=start_date.replace(2019)) updated_at = fake.date_between(start_date=created_at, end_date='now') completed = fake.boolean(chance_of_getting_true=40) todo = Todo(title=title, description=description, completed=completed, created_at=created_at, updated_at=updated_at) db.session.add(todo) db.session.commit()
def setUp(self): self.todo_name = 'Todo 1' self.todo = Todo(name=self.todo_name)