[Django]-Get a dropdown of states in Django Admin

2👍

You need to use a ForeignKey field.
Make the following changes.

class Business(models.Models):
    id = models.IntegerField(primary_key=True)  
    name = models.CharField(max_length=225, blank=True)  
    address = models.CharField(max_length=150, blank=True)  
    city = models.CharField(max_length=150, blank=True)   
    #state_id = models.IntegerField(null=True, blank=True)  
    # Define a new state field that creates a ForeignKey relationship with States
    state = models.ForeignKey('States', null=True, blank=True)
    zip = models.CharField(max_length=33, blank=True)  
    country = models.CharField(max_length=150, blank=True)  
    url = models.CharField(max_length=765, blank=True)  

class States(models.Model):  
    id = models.IntegerField(primary_key=True)  
    name = models.CharField(max_length=96)  
    state_abbr = models.CharField(max_length=24, blank=True)

    #Define the __unicode__ method, which is used by related models by default.
    def __unicode__(self):
        return self.state_abbr

By default ForeignKey fields append ‘_id’ to the field name when creating the column name in the database. So, the new “state” field in the Business class will automatically use the column “state_id” that you’ve previously defined, unless you’ve changed some of the default behavior of Django.

For more on this:

  1. Check out Django’s documentation of
    the ForeignKey field
  2. Search “ForeignKey” on stackoverflow.com
👤Walter

11👍

An alternative that doesn’t require a separate state table:

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

class Business(models.Models):
    ...
    state = models.CharField(max_length=2, choices=STATE_CHOICES, null=True, blank=True)  
    ...
👤Dave

7👍

Edit in 2015 (django 1.8)

you should check the django official localflavor repo: https://github.com/django/django-localflavor.

from localflavor.us.models import USStateField

class Business(models.Models):
    …
    state = USStateField(null=True, blank=True)
    …

Some tests are available on the repo for this specific usage.

Docs available here.

👤vinyll

Leave a comment