2015-12-08 85 views
0

我想添加一個inlineformset到我的CreateView,因此用戶可以在父窗體中添加多個子項。表單生成正確,但是當我點擊提交按鈕時,什麼也沒有發生。Django的:Formset提交按鈕不工作

models.py

class Parent(models.Model): 
    ... 
class Child(models.Model): 
    parent = models.ForeignKey(Parent) 
    ... 

views.py

class ParentCreate(CreateView): 
    model = Parent 
    form_class = ParentForm 

    def get(self, request, *args, **kwargs): 
     self.object = None 
     form_class = self.get_form_class() 
     form = self.get_form(form_class) 
     Child_form = ChildFormSet() 
     return self.render_to_response(
      self.get_context_data(form=form, 
            child_form=child_form, 
            formset=ChildFormSet)) 

    def post(self, request, *args, **kwargs): 
     self.object = None 
     form_class = self.get_form_class() 
     form = self.get_form(form_class) 
     child_form = ChildFormSet(self.request.POST) 
     if form.is_valid() and child_form.is_valid(): 
      return self.form_valid(form, child_form) 
     else: 
      return self.form_invalid(form, child_form) 

    def form_valid(self, form, child_form): 
     self.object = form.save() 
     child_form.instance = self.object 
     child_form.save() 

     return HttpResponseRedirect(self.get_success_url()) 

    def form_invalid(self, form, child_form): 
     return self.render_to_response(
      self.get_context_data(form=form, 
            child_form=child_form, 
            formset=ParentFormSet)) 

forms.py

class ParentForm(ModelForm): 
    class Meta: 
     model = Parent 
     exclude = ('creation', 'last_modified') 


ChildFormSet = inlineformset_factory(Parent, Child, extra=10, 
                 exclude=('creation', 'last_modified'), can_delete=False) 

template.html

<form method="POST" action=".">{% csrf_token %} 
    {{ form|crispy }} 

    {% crispy formset %} 

    <input class="btn btn-primary" type="submit" value="Submit" /> 

</form> 
+0

你可以顯示你的模板? –

+0

意識到我錯過了。它已被添加 – user3972986

+0

我們都有相同的錯誤。我的帖子是[提交按鈕formset不起作用](http://stackoverflow.com/questions/34693617/uploading-multiple-images-in-django-for-a-single-post%22Subimit%20button%20do%20not %20work%22) – Pau

回答

0

我解決我的問題,當我把我的主要形式身體<table> ... </table>

這樣的:

<form id="CreateExamForm" method="POST" enctypr="multipart/form-data"> 
        {% csrf_token %} 
        <table> 
         <div class="panel panel-success"> 
          <div class="panel-heading"> 
           <h3 class="panel-title">Classe - Matière - Date</h3> 
           <span class="pull-right"><i class="glyphicon glyphicon-chevron-up"></i></span> 
          </div> 
          <div class="panel-body"> 
           {% crispy doc_form %} 

           {{ file_form_set.management_form }} 
           {% for f_form in file_form_set %} 
            <div class="form-inline"> 
             {% crispy f_form %} 
            </div> 
           {% endfor %} 
          </div> 
         </div> 
        </table> 
        <input type="submit" value="Add recipe" class="submit" /> 
       </form>