I want to send variables to a form in my Django project so that my form's sav开发者_如何学Pythone method associates the correct object with the foreign key in the model.
I tried setting it in the init method, but that doesn't seem to work.
Here is my Form's init:
def __init__(self, rsvp, max_guests=2, *args, **kwargs):
super(RSVPForm, self).__init__(*args, **kwargs)
self.rsvp = rsvp
self.max_guests = rsvp.max_guests
I think you may be looking for initial
:
Use initial to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.
Pulling directly from the docs:
class CommentForm(forms.Form):
name = forms.CharField(initial='class')
url = forms.URLField()
comment = forms.CharField()
f = CommentForm(initial={'name': 'instance'})
This would yield a form with the initial value of name
being 'instance'.
精彩评论