0

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?

1 Answer 1

1

Just use ModelChoiceField for your country field.

And don't forget to define __unicode__ method of the model.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually, for my current setup ModelChoiceField won't give me exactly what I need. I'm not using the PKs to pass around the value, as I need to use the two-letter country code when passing the values.
@TK Kocheran And why not to use your two-letter country code as pk?
...because I'm already using my PK as the UN assigned country code for each country.
@TK Kocheran I don't think I understand well your task. Why can't you use pk for select's value?
By looking at the source, I think there's a way it would work... thanks for the tip!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.