Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django localflavors US

The following shows up instead of a field in my template.

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

my template has

{{ form.state }}

what could the issue be?

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()

also is there anyway i can make the state and zip optional?

like image 254
Eva611 Avatar asked Jun 21 '11 03:06

Eva611


1 Answers

To limit the choices to a 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 a field optional in a form, add blank = True to that 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 you can find in the localflavor documentation. STATE_CHOICES is the most inclusive, but that may not be what you desire. If you just want 50 states, plus DC, use US_STATES.


This answer assumes you're using ModelForms. If you aren't, you should be. Once you've made your model, you should follow DRY and create basic forms like so:

from django.forms import ModelForm

class ExampleForm(ModelForm):
    class Meta:
        model = ExampleLocation

And it inherits your fields from your model. You can customize what fields are available, if you don't want the whole model, with other class Meta options like fields or exclude. Model forms are just as customizable as any other form, they just start with the assumption of your model's fields.

like image 64
Frank Crook Avatar answered Oct 10 '22 23:10

Frank Crook