Possible Duplicate:
Validating a form with overloaded init
I’ve spent the entire afternoon trying to figure out what I’m doing wrong here, and I know it’s going to be something face-palmingly stupid. When the user fills out a form, the location selection box depends on the country of the user and lists different cities accordingly.
Model & Modelform
class Cars(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=25)
location = models.PositiveIntegerField(default=1)
created = models.DateTimeField(default=utc_time)
class CarsForm(ModelForm):
def __init__(self, country, *args, **kwargs):
super(CarsForm, self).__init__(*args, **kwargs)
self.fields['location'] = forms.ModelChoiceField(queryset=Cities.objects.filter(country=country))
class Meta:
model = Cars
exclude = ('owner', 'created',)
View
def new_car(request):
if request.method == u'POST' and request.is_ajax():
form = CarsForm(request.POST)
if form.is_valid():
etc...
Following advice from stackoverflow, I edited the modelform init to allow the country variable to be passed. The form creation and html displays fine and everything works great, only now the form won’t validate.
UPDATE:
Ok, it looks like I (meaning ‘YOU’) got it working. Several things were ugly, and once fixed it works ok:
- the location field type was changed to foreignkey, correcting the
data mismatch issue - the init was revised to accept country as a kwarg
- the form validation now passes the variable as a kwarg
CarsForm(request.POST, country=country)
SUCCESS! In under an hour. Thanks so much everyone!!
Either this is the solution, or your copy-and-pasting has problems
;)You’ve correctly defined the over-ridden
__init__method, but you’re not actually passing acountryparameter; doing so would look like this:This means that
request.POSTalways gets stored incountryand never passed on to the parent class’s__init__method.If the form gets no data,
is_valid()will always returnFalse.A side-note: where does
SkillFormcome from? Should beCarsForm.