I have pretty complicated form items ;)
Here's my view for serving my form:
def view(request):
if request.method == "POST":
form = forms.ProfileEditForm(request.POST)
else:
form = forms.ProfileEditForm(initial={'country': request.user.profile.country})
return direct_to_template(request, "name/of/template.html",
{"form": form, "countries": Country.objects.all()})
Here's what the country model looks like:
class Country(models.Model):
iso2 = models.CharField()
iso3 = models.CharField()
name = models.CharField()
Here's what my form's clean() method looks like (highly simplified):
def clean(self):
self.cleaned_data['country'] = Country.objects.get(iso2=self.cleaned_data['country'])
return self.cleaned_data
Here's how I'm rendering it in a template:
<select name="country"{% if form.country.value %} data-initialvalue="{{form.country.value.iso2}}"{% endif %}>
{% for country in countries %}
<option value="{{country.iso2}}"{% if country.iso2==form.country.value.iso2 %} selected{% endif %}>{{country.name}}</option>
{% endfor %}
</select>
However, I'm noticing that what actually ends up being delivered to my template isn't a Country object, but a string of my input data, such as "US". When I initially render my template with the initial data, things look fine, but when validation fails, things get messed up. What should I do, and what am I doing wrong?