问题
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