Django formset没有modelform无法正常工作

时间:2016-04-27 21:48:25

标签: python django django-forms

我试图创建我的第一个django formset。我关注this example,但无法创建仅包含一个模型的表单集(其他表单是常规的,没有附加模型)。

  

forms.py(相关部分)

class ArrivalForm(forms.ModelForm):
    class Meta:
        model = Reservation
        fields = ['passenger_name', 'passenger_lastname', 'passenger_email', 'author_chain' ]

    helper = FormHelper()
    helper.form_tag = False
    helper.label_class = 'col-lg-3'
    helper.field_class = 'col-lg-9'

class RouteForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        super(RouteForm, self).__init__(*args, **kwargs)


    place = forms.CharField(max_length=255)
    time = forms.TimeField()

RouteInlineFormset = inlineformset_factory(ArrivalForm, form=RouteForm, extra=2, can_delete=True)
  

错误

TypeError at /reservations/create/arrival
inlineformset_factory() takes at least 2 arguments (4 given)
  

问题

如何为non-model表单创建新的formset。在documentation我只能找到如何为ModelForm执行此操作。

1 个答案:

答案 0 :(得分:3)

formset_factory是您在没有模型的情况下创建表单集所需的。您可以阅读详细信息here。这是一个例子。

from django.forms import formset_factory
from django.shortcuts import render
from myapp.forms import ArticleForm, BookForm

def manage_articles(request):
    ArticleFormSet = formset_factory(ArticleForm)
    BookFormSet = formset_factory(BookForm)
    if request.method == 'POST':
        article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')
        book_formset = BookFormSet(request.POST, request.FILES, prefix='books')
        if article_formset.is_valid() and book_formset.is_valid():
            # do something with the cleaned_data on the formsets.
            pass
    else:
        article_formset = ArticleFormSet(prefix='articles')
        book_formset = BookFormSet(prefix='books')
    return render(request, 'manage_articles.html', {
        'article_formset': article_formset,
        'book_formset': book_formset,
    })