在django模板中包含两个management_forms;只返回一个

时间:2014-08-06 21:39:35

标签: django django-forms

我正在尝试在我的模板中包含两个inline_formsets,但由于某种原因,只为其中一个返回了management_form数据。

models.py:

class Author(models.Model):
    name = models.CharField(max_length=20)

class Book(models.Model):
    title = models.CharField(max_length=20)
    author = models.ForeignKey(Author)

class Magazine(models.Model):
    title = models.CharField(max_length=20)
    author = models.ForeignKey(Author)

forms.py:

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

BookFormset = inlineformset_factory(Author, Book, fields=('title',), can_delete=True)
MagazineFormset = inlineformset_factory(Author, Magazine, fields=('title',), can_delete=True)

views.py:

def add_author(request):
    form = AuthorForm()
    book_formset = BookFormset(instance=Author(), prefix='magazines')
    magazine_formset = MagazineFormset(instance=Author(), prefix='magazines')

    if request.method == 'POST':
        form = AuthorForm(request.POST)
        if form.is_valid():
            author = form.save()
            book_formset = BookFormset(request.POST, instance=author, prefix='books')
            magazine_formset = MagazineFormset(request.POST, instance=author, prefix='magazines')
            if book_formset.is_valid() and magazine_formset.is_valid():
                book_formset.save()
                magazine_formset.save()
                return HttpResponseRedirect('/')

    return render(request, "form.html", {'form': form, 'book_formset': book_formset, 
                            'magazine_formset': magazine_formset, 'action': "Create"})

最后,form.html:

<html>
<body>
<h4>{{ action }}</h4>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<h3>Books</h3>
{{ magazine_formset.management_form }}
{{ book_formset.management_form }}
{{ book_formset }}
<h3>Magazines</h3>
{{ magazine_formset }}
<input type="submit" value="submit" />
</form>
</body>

这似乎应该相当简单,但我仍然得到

ValidationError at /add/
[u'ManagementForm data is missing or has been tampered with']

以下是显示book_formset.management_form未通过的POST数据:

POST

变量值

杂志 - INITIAL_FORMS u&#39; 0&#39;

杂志 - 1-title u&#39; sksd&#39;

命名为&#39; sdf&#39;

杂志 - 1-id u&#39;&#39;

杂志 - 2-title u&#39;&#39;

杂志 - 2-id u&#39;&#39;

杂志-MAX_NUM_FORMS u&#39; 1000&#39;

杂志-0-作者u&#39;&#39;

杂志 - 0-title u&#39; sdlkfs&#39;

杂志 - 1-author u&#39;&#39;

杂志-0-id u&#39;&#39;

杂志-TOTAL_FORMS u&#39; 3&#39;

csrfmiddlewaretoken u&#39; oJ82pScHeSMKzcE7E19xZEa75nrBKyro&#39;

杂志 - 2-author u&#39;&#39;

我错过了什么?

1 个答案:

答案 0 :(得分:1)

在视图的GET部分,您已经为两个表单集添加了前缀“杂志”。