Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30845

Filter ForeignKeyFeild Choices in field by value in other field

So I have a few Django models that look like this:

class City(models.Model):
   name = models.CharField("City", max_length=200)

   def __unicode__(self):
     return self.name

   class Meta:
     verbose_name_plural="Cities"

 class Neighborhood(models.Model):
   name = models.CharField("Neighborhood", max_length=200)
   city = models.ForeignKey(City, verbose_name='City')

   def __unicode__(self):
     return self.name + " in " + str(self.city)
 class Application(models.Model):
   NUM_BED_CHOICES = ((1, u'Rollin Solo'), (2, u'2 Bedrooms'), (3, u'3 Bedrooms'), (4, u'4 Bedrooms'),)
   LEASE_LENGTH_CHOICES = ((u'SUM', u'Summer'), (u'1YR', u'One Year'), (u'2YR', u'Two Years'), (u'2Y+', u'Two Years+'),)

   user = models.ForeignKey(User)
   neighborhood = models.ForeignKey(Neighborhood, verbose_name="Neighborhood")
   moveinDate = models.DateField("Move-in Date")
   numberOfBedrooms = models.SmallIntegerField("Number of Bedrooms", choices=NUM_BED_CHOICES)
   leaseLength = models.CharField("Lease Length", max_length=3, choices=LEASE_LENGTH_CHOICES)
   bedroomBudget = models.DecimalField("Budget Per-Bedroom", max_digits=10, decimal_places=2)
   hasPet = models.BooleanField("Has Pet")
   hasBeenPlaced = models.BooleanField("Has Been Placed", default=False)

   class Meta:
     verbose_name = "Application"

And I have a Model Form for the Appliction, that's just this:

class ApplicationForm(ModelForm):
  class Meta:
    model = Application
    exclude = ('hasBeenPlaced','user',)

I'd like to be able to add a selection widget to my ApplicationForm that allows the users to select from one of the City Objects in my City model, and then filter their choices of neighborhoods based on that selection. For example: if they select 'Chicago' in this extra field I want to add, all of the neighborhoods that weren't in Chicago would be removed from the list of available neighborhoods to select from in the ApplicationForm. Is this possible with Django? If so, how would one go about accomplishing such a task?

Upvotes: 1

Views: 287

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239460

Technically, this is no longer in the realm of Django. Once the page is rendered, Django is done. Anything like this requires JavaScript and specifically AJAX. You just create a view to return neighborhoods for a city in JSON, then use AJAX to fetch that response whenever the city selectbox's onchange event is fired. Use use the JSON to construct new options for the neighboorhood selectbox, and then replace the old options with that.

There's a million questions on StackOverflow regarding how to specifically do all that -- many written by myself.

Upvotes: 2

Related Questions