Admin site - prepopulating field based on foreign key

44 views
Skip to first unread message

dod...@gmail.com

unread,
Nov 3, 2016, 5:21:14 PM11/3/16
to Django users
I'm having trouble with my admin site, would appreciate any pointers.

I have these three models in my database with relationships as shown:

class Customer(models.Model):
  name=models.CharField(max_length=30)

class Location(models.Model):
  name=models.CharField(max_length=30)
  customer = models.ForeignKey(Customer, on_delete = models.PROTECT)

class License(models.Model):
  location=models.ForeignKey(Location, on_delete=models.PROTECT)


When the user creates a new License on the admin site, at the moment they have to choose what location the License is at via a dropdown box (a very long, confusing list), or create a new one if necessary.

It would be much better if they could choose what Customer the license belongs to, and then choose the Location from the list of locations that have that customer as their foreign key.  They still may need to add a new location or even a new customer when doing this.

What is the easiest way to do this on the admin site?  

I am thinking that I will have to create a new widget with two dropdowns, and have the selection of the first make an AJAX query to populate the second.  Am I on the right track?  How can I then tie in this custom widget for the location field in License?

I'm sure that this isn't a unique situation, but I haven't been able to find any tutorial or solution showing how to handle a follow-the-foreign key relationship.

Derek

unread,
Nov 4, 2016, 3:36:58 PM11/4/16
to Django users

Rafael E. Ferrero

unread,
Nov 4, 2016, 7:00:20 PM11/4/16
to django...@googlegroups.com
Or you can filter the select with this


Rafael E. Ferrero

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3dddffa5-a4c1-4e64-a3fe-a15b0d39c701%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

dod...@gmail.com

unread,
Nov 7, 2016, 10:27:20 PM11/7/16
to Django users
Thanks, smart-selects has shown me how to do exactly what I wanted.
Reply all
Reply to author
Forward
0 new messages