Question

A user has to select a vehicle type, then based on his selection he then has options of selecting a vehicle model, then based on that selection he will have the option of viewing specific colours available for that model.

There are separate django models for each of vehicle, model, and colour, where each vehicle instance has many models (many to many field) and each model has colours (many to many field).

How would you create a template so that the user is able to dynamically do this? I don't want to be redirected to different views. I'm thinking I would need to use jquery so that the user can select the vehicle from a drop down box, then based on his choice another drop down box appears etc..

Any ideas?

Was it helpful?

Solution

My approach would be to use ajax to dynamically change the content of the select boxes. There are many ways to implement this. Here is one...

  • Create 3 select boxes (vehicle, model, color)
  • Populate the first one with all a blank entry plus all vehicles
  • Trap the onchange event for the vehicle and model and create corresponding javascript functions.

Here is the sudo code for the vehicleChange function:

  • Clear all model select options
  • Clear all color select options
  • fetch model select options from server using ajax
  • populate model select box.

Here is the sudo code for modelChange function:

  • Clear color select options
  • fetch color select options from server using ajax
  • populate color select box.

So now what happens is:

  • Because you are using ajax your page will not refresh or redirect.
  • Your model for "model" and "color" remain as simple as possible
  • Your view for "model" and "color" become very small. One possible view would yield something like:

    <option value="Red">Red</option>
    <option value="White">Blue</option>
    <option value="Blue">Blue</option>

To change the options in the select boxes you could use jquery to grab the select box and replace the html with the results from the ajax call.

OTHER TIPS

You could use dajax, a ajax library for django. On their website they even have a very similar example --> http://www.dajaxproject.com/forms/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top