0

I want my "Location" drop down list to be dependent on my "Client" drop down list. My models:

class Client(models.Model):
  name = models.CharField(max_length=50)

class Location(models.Model):
  name = models.CharField(max_length=50)

What is the next step after this?

Should I put a FK somewhere?

What is the AJAX code for this?

Lloyd
  • 161
  • 3
  • 11

1 Answers1

0

If you want to display two dropdowns, first one with Client options and second one with Location options, with Locations changing on Client dropdown change you should add a js event handler, for example with jQuery:

$(document).on('change', '#clients', () => { 
    ...call locations endpoint and update locations options... 
})

On backend append your Location model with a Client FK and make an endpoint for path app/locations/<int:client_id>/ where you select Locations based on a Client:

from django.shortcuts import get_object_or_404
...
def locations(request, client_id):
    client = get_object_or_404(Client, id=client_id)
    locations = Location.objects.filter(client=client)
    return JsonResponse(dict(locations=locations), status=200)
Kyryl Havrylenko
  • 674
  • 4
  • 11
  • Where would i code "def locations..."? Is it under models.py or views.py? Also how do i call the endpoints in the jQuery? – Lloyd Jan 28 '19 at 08:46
  • `def locations` is a view, so it should be inside `app/views.py`. I made an example with function-based view, you can use class-based if you like it more. To make an ajax call in jQuery look at this [question](https://stackoverflow.com/questions/9436534/ajax-tutorial-for-post-and-get). – Kyryl Havrylenko Jan 28 '19 at 10:41