I'm trying to build a form where a select list can be initialized from a tuple parameter I pass in on creation of the form object.
I tried doing the following, which worked for CREATING the form. But when I try to submit the form, I get an is_valid() = false error. In the example below the myrooms variable is the data I'd like to dynamically load upon initialization of the form. Any help here?
class SessionInfoForm(forms.ModelForm):
def __init__(self, myrooms = None, *args, **kwargs):
super(SessionInfoForm, self).__init__(*args, **kwargs)
if myrooms != None:
self.fields['room'].choices = myrooms
class Meta:
model开发者_开发百科 = SessionInfo
fields = ["title", "room", "viewer_limit", "starttime", "endtime", "billing_type", "billing_value"]
Your are probably forgetting to pass the same list to myrooms
when validating the results.
You have to pass it both for the rendering and the validating.
just change self.fields['room'].choices = myrooms
to self.fields['room'].widget.choices = myrooms
, i have already edited that into your question
精彩评论