django inlineformset_factory extra attribute being ignored?

回眸只為那壹抹淺笑 提交于 2019-12-23 03:32:14

问题


I am trying to render an inlineformset but the "extra" attribute seems to be ignored. Consider the following models:

 class Foo_model(models.Model):     
     fooName = models.CharField(max_length=LIL_STRING)
     bars    = models.ForeignKey("Bar_model")

 class Bar_model(models.Model):     
     barName = models.CharField(max_length=LIL_STRING)

forms:

 class Foo_form(ModelForm):    
     class Meta:
         model = Foo_model

 class Bar_form(ModelForm):    
     class Meta:
         model = Bar_model

 Bar_formset = inlineformset_factory(Foo_model,Bar_model,formset=Bar_form,extra=23)

view:

 def ViewFoo(request, model_id=False):
     if model_id:                  
         model = Foo_model.objects.get(pk=model_id)
     else:
         model = Foo_model()

     form = Foo_form(instance=model)    
     formset = Bar_formset(instance=model)

     return render_to_response('form.html', {'form' : form, 'formset' : formset }, context_instance=RequestContext(request))

and template:

 <html>
   <form method="POST" action="">
     {% csrf_token %}
     <div>
       {{ form }}
       {{ formset }}
     </div>
     <input class="button" type="submit" value="Submit"/>
   </form>
 </html>  

This only shows one instance of Bar_form, when it ought to show 23 ("extra=23"). Any ideas what I'm doing wrong?

Thanks


Update:

It turns out that part of the problem is that all of my model classes inherit from the same base class. If I make them just inherit from models.Model, then the problem goes away (though other problems rear their ugly heads). I still want them to inherit from a single class, so my original question remains.


Update Update:

Making my models' base class abstract:

 class BaseClass(models.Model):
     class Meta:
         abstract = True

Seems to do the trick. I can now have ForeignKeys and ManyToManyFields between my classes.


回答1:


Since the foreign key exists in the Foo model, you'll need to create a Foo FormSet (otherwise, logically, it doesn't make sense as to what the form would contain).



来源:https://stackoverflow.com/questions/8855567/django-inlineformset-factory-extra-attribute-being-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!