Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make Django's USStateField() to not have a pre-selected value?

I use USStateField() from Django's localflavor in one of my models:

class MyClass(models.Model):
   state  = USStateField(blank=True)

Then I made a form from that class:

class MyClassForm(forms.ModelForm):
    class Meta:
        model   = MyClass

When I display the form, the field "State" is a drop-down box with "Alabama" pre-selected.

Is there any way to make the drop-down box to show no pre-selected value at all?

like image 675
Continuation Avatar asked Dec 02 '09 05:12

Continuation


2 Answers

This seems to be a known issue (though I'm not aware of a ticket - I'd double-check there's not a ticket for it, and if not, file it):

from django.contrib.localflavor.us.us_states import STATE_CHOICES
from django.contrib.localflavor.us.forms import USStateField

class YourModelForm(forms.ModelForm):
    class Meta:
        ...

    YOUR_STATE_CHOICES = list(STATE_CHOICES)
    YOUR_STATE_CHOICES.insert(0, ('', '---------'))
    state = USStateField(widget=forms.Select(
            choices=YOUR_STATE_CHOICES))

Above code from here.

like image 137
Dominic Rodger Avatar answered Nov 15 '22 22:11

Dominic Rodger


I don't really like the idea of inserting ----- into the list manually. When the field is set to blank=True, the blank option should appear at the top of the picklist automatically. Plus, if your state field is on Profile and you're using django-profiles, then you end up in the position of having to modify a reusable app.

I find it easier and cleaner to just copy the STATE_CHOICES tuple from the file contrib/localflavor/us/us_states.py into the constants.py in my project, and then in models.py:

import constants
state = models.CharField(blank=True, max_length=2, choices=constants.STATE_CHOICES) 

The blank=True option then works as expected without having to monkeypatch the list.

like image 29
shacker Avatar answered Nov 15 '22 22:11

shacker