我正在django中创建一个待办事项应用程序,并且在更新任务时,我想用以前的数据自动填充字段。我在哪里弄糟?
这也是我的views.py:-
task = get_object_or_404(ToDoList, id=id)
if request.method == "POST":
form = UpdateTaskForm(request.POST)
if form.is_valid():
task.description = form.cleaned_data['description']
task.save()
form.save()
return redirect(reverse('list'))
else:
form = UpdateTaskForm(instance=task)
context = {
'form':form,
'task':task,
}
return render(request, 'TaskList/update.html', context)
这是我的表格。py:-
class Meta:
model = ToDoList
fields = ['title', 'description', 'due_date', 'completed']
这是我的模板文件:-
{% load crispy_forms_tags %}
{% block title %} Updating task {% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success" value="Submit"> Save </button>
</form>
{% endblock %}
这是我的模型。py:-
from django.utils import timezone
# Create your models here.
class ToDoList(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(help_text='Explain your task!', blank=True)
created_date = models.DateTimeField(default=timezone.now())
due_date = models.DateTimeField(default=timezone.now())
completed = models.BooleanField(default=False)
#Author foreign key
def __str__(self):
return self.title
答案 0 :(得分:0)
如果您要更新实例,则还必须在POST方法中传递相同的实例,因此在
之后 if request.method == "POST":
添加form = UpdateTaskForm(request.POST,instance=task)
我猜您使用的是脆皮表格,所以根据这个问题here他们正在使用{% crispy form %}
渲染表格,而不是像{{ form|crispy }}
那样做