Django localflavors USA

My template displays the following field.

<django.contrib.localflavor.us.forms.USStateSelect object at 0x92b136c> 

In my template

 {{ form.state }} 

what could be the problem?

 class RegistrationForm(forms.Form): first_name = forms.CharField(max_length=20) last_name = forms.CharField(max_length=20) phone = USPhoneNumberField() address1 = forms.CharField(max_length=45) address2 = forms.CharField(max_length=45) city = forms.CharField(max_length=50) state = USStateSelect() zip = USZipCodeField() 

too, can I make the state and zip optional?

+7
source share
1 answer

To limit the selection to the drop-down list, use us.us_states.STATE_CHOICES in your model and use us.forms.USStateField() instead of us.forms.USStateSelect() in your forms.

To make the field optional on the form, add blank = True to this field in the model.

 from django.contrib.localflavor.us.us_states import STATE_CHOICES from django.contrib.localflavor.us.models import USStateField class ExampleLocation(models.Model): address1 = models.CharField(max_length=45) #this is not optional in a form address2 = models.CharField(max_length=45, blank = True) #this is made optional state = USStateField(choices = STATE_CHOICES) 

Instead of STATE_CHOICES there are several options that you can find in the localflavor documentation . STATE_CHOICES is the most inclusive, but it may not be what you want. If you want only 50 states, plus DC, use US_STATES .


This answer assumes you are using ModelForms . If you do not, you must be. Once you have created your model, you must follow DRY and create basic forms:

 from django.forms import ModelForm class ExampleForm(ModelForm): class Meta: model = ExampleLocation 

And it inherits your fields from your model. You can configure which fields are available if you do not want the entire model, with other class Meta options such as fields or exclude . Model forms are just as customizable as any other form, they only begin with the assumption of your model fields.

+9
source

All Articles