简体   繁体   中英

How do I get a cascading drop down selection box with my foreign keys in Django?

So I have a model called Car with a foreign key of a Manufacturer model. I also have a CarCharacterisitcs model with a foreign key of Car .

This is what the code looks like:

class Car(models.Model):
    idcar = models.AutoField(primary_key=True)
    manufacturer = models.ForeignKey(Manufacturer, null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=765)

class Manufacturer(models.Model):
    idmanufacturer = models.AutoField(primary_key=True)
    name = models.CharField(max_length=765)

class CarCharacteristics(models.Model):
    idcar_characteristics = models.AutoField(primary_key=True)
    car = models.ForeignKey(Car, on_delete=models.PROTECT)

I am making a page that lets you add CarCharacteristics .

This is my form and view:

class CarCharacteristicsForm(ModelForm):
    class Meta:
        model = CarCharacterisitics

def add_car_characteristics(request):
    if request.method == 'POST':
        car_char_form = CarCharacterisiticsForm(request.POST)
        if car_char.is_valid(:
            car_char_form.save()
            return HttpResponseRedirect('/cars/car-characterisitcs')
    else:
        car_char_form = CarCharacterisiticsForm()
    return render(request, 'car_characteristics/add_car_characteristics.html',{'car_char_form': car_char_form,})

In my html page, I have this:

<h1>Car Characteristics</h1>
<form action="." method="POST">
{% csrf_token %}
    <table id="characteristics_table">
        <tr>
        <td>
        <table id="car_characterisitcs_table">
            <td>{{ char_char_form.as_table }}</td>
        </table>
        </td>
        </tr>
    </table>
    <p><input type="submit" value="Submit"></p>
</form>

When this form is displayed, I have a drop down select field with all my possible Car models. What I want is to have two select fields. I want the first to let you be able to select the Manufacturer and then the second to display all the possible Cars that have that manufacturer. Then when you submit the form, it assigns the Car you selected to the Foreign Key of the CarCharacterisitcs model.

If you go look at Advance Auto Parts , when you click "Your Vehicle", that is what I want to have. How do I do that?

You need to use AJAX to fetch the data for a selected manufacturer and populate the car field accordingly. This needs to be done inside the view code and return the car fetched data in to the template and use the template language to populate the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM