Django Dynamic Drop-down List from Database

后端 未结 2 386
萌比男神i
萌比男神i 2021-01-31 23:15

I wanted to develop a Django app and one of the functionalities I\'d like to have is dynamic drop-down lists...specifically for vehicle makes and models...selecting a specific m

2条回答
  •  一向
    一向 (楼主)
    2021-02-01 00:14

    The 3 things you mention being common, make, model, year, would be the 3 input values. When given to the server, an object containing the details would be returned to the calling page. That page would parse the object details (using JavaScript), and update the UI to display them to the user.

    From the Django side, there needs to be the facilities to take the 3 inputs, and return the output. From the client-side, there needs to be the facilities to pass the 3 inputs to the server, and then appropriately parse the server's response.

    There is a REST api framework for Django that makes it rather easy to add the "api" mentioned above -- Piston. Using Piston, you'd simply need to make a URL for that resource, and then add a handler to process it. (you'll still need to skim the Piston documentation, but this should give you an idea of what it looks like)

    urls.py:
    vehicle_details = Resource(handler=VehicleDetails)
    url(r'^vehicle/(?.*)/(?.*)/(?[a-z]{1,4}), vehicle_details, name='vehicle_details'),
    
    handler.py:
    class VehicleDetails(BaseHandler):
        methods_allowed = ('GET',)
        model = Vehicles  #whatever your Django vehicle model is
    
        def read(self, request, *args, **kwargs):
            # code to query the DB and select the options
            # self.model.objects.filter()...            
            # Build a custom object or something to return
    
            return custom_object
    

    This simply sets up the url www.yoursite.com/vehicle/[make]/[model]/[year]/json to return a custom data object in JSON for jquery to parse.

    On the client side, you could use jquery to setup an event (bind) so that when all 3 drop downs have a value selected, it will execute a $.get() to the api URL. When it gets this result back, it passes it into the Jquery JSON parser, and gives the custom object, as a javascript object. That object could then be used to populate more drop down menus.

    (Big warning, I just wrote the following off the top of my head, so it's not meant to be copy and pasted. It's just for the general idea.)

    
    

提交回复
热议问题