开发者

How can I send variables to my forms on init in Django?

开发者 https://www.devze.com 2022-12-29 22:13 出处:网络
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 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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号