2016-04-27 120 views
1

我想創建我的第一個django formset。我正在關注this example,但無法創建僅有一個模型的表單集(其他表單是常規的,沒有附加模型)。Django formset沒有模型不起作用

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表單創建新的表單集。在documentation我只能找到如何爲ModelForm做到這一點。

回答

2

formset_factory是您需要創建一個沒有模型的formset的人。你可以閱讀詳細信息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, 
    })