我的目标是使用一个表单列出同一表单的5个版本。提交表单时,应在DB中创建填写的表单。
我的问题是表格会重新填充数据。这很糟糕。关于我可能做错什么的任何想法?
Models.py
from django.db import models
from django.contrib.auth.models import User
PRIORITIES = (
('1', 'High'),
('2', 'Medium'),
('3', 'Low'),
)
class Todo(models.Model):
task = models.CharField(max_length=200)
owner = models.ForeignKey(User)
priority = models.CharField(max_length=10, choices=PRIORITIES)
creation_date = models.DateField('date created', blank=True, null=True)
due_date = models.DateField('date due', blank=True, null=True)
completion_date = models.DateField('date complete', blank=True, null=True)
completed = models.BooleanField()
def __unicode__(self):
return self.task
Forms.py
from django import forms
from pooflinger.todo.models import Todo
from django.forms import ModelForm
from django.forms.models import modelformset_factory
TodoFormSet = modelformset_factory(Todo, max_num=2,)
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
Views.py
def todo_form(request):
user = request.user
current_date = datetime.now()
if request.method == 'POST':
formset = TodoFormSet(request.POST)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/todo/')
else:
formset = TodoFormSet()
return render_to_response('todo/todo_formset.html', {
'user': user,
'formset': formset,
'current_date': current_date,
}, context_instance=RequestContext(request))
表单模板
<form method="post" action="">
<table>
{{ formset }}
</table>
<button class="glue primary" type="submit" value="Submit">Submit</button></p>
</form>
答案 0 :(得分:3)
我需要添加一个查询集
<强>编辑
qs = Todo.objects.none()
formset = TodoFormSet(queryset=qs)
最终代码
def todo_form(request):
user = request.user
current_date = datetime.now()
qs = Todo.objects.none()
if request.method == 'POST':
formset = TodoFormSet(request.POST)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/todo/')
else:
formset = TodoFormSet(queryset=qs)
return render_to_response('todo/todo_formset.html', {
'user': user,
'formset': formset,
'current_date': current_date,
}, context_instance=RequestContext(request))