Micah Pearce
Micah Pearce

Reputation: 1945

What's a good way to create a multiselect US state field

I'm looking to create a multi-select US state field.

One way to do it is to create a Model and then use a ManyToManyField on another Model. See my example below:

class States(models.Model):
   ALABAMA= 1
   ALABAMA= 2
   ARIZONA= 3
   GEO_CHOICES = (
       (ALABAMA, 'alabama'),
       (ALABAMA, 'alaska'),
       (ARIZONA, 'arizona'),
   )

   id = models.PositiveSmallIntegerField(choices=GEO_CHOICES, primary_key=True)

   def __str__(self):
     return self.get_id_display()

class Profile(models.Model):
    user ...
    state = models.ManyToManyField(States)

Question 1: Is there a way that I can include the 2 digit short code in my code below?

Question 2: Is there a default state list? What about zip codes our state counties?

Upvotes: 1

Views: 943

Answers (1)

Ralf
Ralf

Reputation: 16505

Regarding you first question:

Is there a way that I can include the 2 digit short code in my code below?

It is just like you already said in a comment: you should probably create a model State with all the info like code and abbreviation.

But look at the packages I linked below, maybe they are helpful in your quest.


As to your second question:

Is there a default state list? What about zip codes our state counties?

You could look into:

  1. the official django-localflavor repo.
  2. this 6-year-old repo django-localflavor-us very similar to the previous one I mentioned.

Upvotes: 1

Related Questions