Django:如何使用与用户具有多对一关系的inline_formset创建表单

时间:2017-04-09 17:34:49

标签: python django forms django-forms inline-formset

我正在尝试使用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。我不确定哪种方法更可取。

我有两个问题。

  1. 为什么我收到上述错误?
  2. 我应该将formset设置为用户实例而不是case吗?
  3. 由于

1 个答案:

答案 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})