Reputation: 3915
I have this model:
class option(models.Model):
warval = models.ForeignKey(war)
caption = models.CharField(max_length=20)
text = models.TextField(blank=True,null=True)
url = models.URLField(blank=True,null=True)
user = models.ForeignKey(User)
And also have following forms:
class text_option(ModelForm):
class Meta:
model = option
exclude = ('url','warval','user')
class url_option(ModelForm):
class Meta:
model = option
exclude = ('text','warval','user')
Suppose I create a formset of the "text_option" form.What I want is to instantiate all the forms in this formset with "war":w and "user":u.How can I do that.Also if that's not possible then what other options do I have?
Upvotes: 1
Views: 348
Reputation: 8488
What you want is posible. I don't remember right now if there is some class-based view that do that automatically for you (i think not), but you can do it manually without much effort.
In your view post method, after you have your forms in formset instantiated (have a look at this) and checked that is valid, you can iterate over formset's forms, and set their user and warval as you want.
Another option is to set user and warval as initial values, so every form in that formset will have the user and warval you want.
If you need an example on how to do all this things, i could try to add some in order to help you, but i think django documentation is the best way to go....
EDIT: As in model's clean method, you can add some "default" values for your formset (or forms in formset) in your formset's clean method. You can try to follow this steps to include your own clean method and then instanciate each form inside your formset like this (Note: i'm not trying this in my computer but it's the way i would do it if i had to):
for form in formset:
form.instance.user = user
form.instance.warval = warval
Hope it helps!
Upvotes: 1