我正在尝试使用Django的inlineformset_factory设置表单。该模型以多对一的关系建立,每个用户将有许多案例。我希望用户添加一个案例。
我遵循了this site
的大纲models.py
class Case(models.Model):
date_due = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
CaseFormset = inlineformset_factory(User,Case,
fields=('date_due',),
can_delete = True)
class CaseForm(forms.ModelForm):
class Meta:
model = Case
fields = ('date_due',)
views.py
@login_required
def add_case(request):
if request.method == 'POST':
form = CaseForm(request.POST)
if form.is_valid():
case = form.save(commit = False)
case_formset = CaseFormset(request.POST, instance = case)
if case_formset.is_valid():
case.save()
case_formset.save()
return redirect('index')
else:
print(form.errors)
else:
form = CaseForm()
case_formset = CaseFormset(instance = Case())
return render(request, 'cases/add_case.html',
{'form':form, 'case_formset':case_formset})
add_case.html
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{{ case_formset.as_p }}
{{ case_formset.management_form }}
<button type="submit">Save changes</button>
</form>
</body>
</head>
</html>
我正在
Exception Type: ValidationError
Exception Value:
['ManagementForm data is missing or has been tampered with']
阅读文档看起来我需要将management_form添加到formset中,我已经完成了。我不知道我哪里出错了。
我还尝试了the docs
的不同方法它看起来与上面略有不同,并尝试使用用户作为实例创建一个formset。我不确定哪种方法更可取。
我有两个问题。
由于
答案 0 :(得分:0)
我明白了!
在views.py中,我需要添加case.user = request.user
所以views.py看起来像
@login_required
def add_case(request):
if request.method == 'POST':
form = CaseForm(request.POST)
if form.is_valid():
case = form.save(commit=False)
case.user = request.user
case_formset = CaseFormset(request.POST, instance = case)
if case_formset.is_valid():
case.save()
case_formset.save()
return redirect('index')
else:
print(form.errors)
else:
form = CaseForm()
case_formset = CaseFormset(instance = Case())
return render(request, 'cases/add_case.html',
{'form':form, 'case_formset':case_formset})