Django Dynamic Drop-down List from Database

2020-05-19 00:48发布

问题:

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 make will update the models list with only the models that fall under that make....I know this is possible in javascript or jQuery (this would be my best choice if anyone has an answer) but I don't know how to go about it.

Also, I'd want the make, model, year and series to be common then the other attributes like color, transmission etc to be variables so that one needs only enter the make, model, year, and series only for a new vehicle. Any ideas would be highly appreciated.

回答1:

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/(?<make>.*)/(?<model>.*)/(?<year\d{2,4}/(?P<emitter_format>[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.)

<script type="text/javascript">

    // On document load
    $(function() {
        $('#dropdown_make').bind('change', checkForValues());
        $('#dropdown_model').bind('change', checkForValues());
        $('#dropdown_year').bind('change', checkForValues());
    });

    function checkForValues() {
        if ($('#dropdown_make').val() && $('#dropdown_model').val() && $('#dropdown_year').val())
            updateOptions();        
    }

    function updateOptions() {
        url = '/vehicle/';
        url += $('#dropdown_make').val() + '/';
        url += $('#dropdown_model').val() + '/';
        url += $('#dropdown_year').val() + '/';
        url += 'json/';
        $.get(url, function(){
            // Custom data object will be returned here
        })
    }
</script>



回答2:

This is uncanny: Dynamic Filtered Drop-Down Choice Fields With Django

His question:

"Here is the situation: I have a database with car makes and models. When a user selects a make, I want to update the models drop-down with only the models associated with that make. ... Therefore I want to use Ajax to populate the data."

You're not the same guy? :)