sidp
sidp

Reputation: 147

Pull select form options from database in Django

I'm making a simple 2-page website that will allow the user to use dropdown boxes or HTML select forms (make, model, trim) on the front page to get information about a car that will be stored in a database. After pressing a search button, the user will then be taken to the page that provides information about the vehicle. I'm very confused as to how I go about linking these dropdown boxes to data from the database in Django.

The Car model I have resides in the models.py of my cardetails app and looks like this so far:

class Car(models.Model):

    make = models.CharField(max_length=50)
    model = models.CharField(max_length=50)
    trim = models.CharField(max_length=50)

    # other info here.

    # Return the actual name of the car instead of "model-object"
    def __str__(self):
        return self.make + " " + self.model + " " + self.trim

Googling about led me to this way of setting up a ModelForm, which resides in forms.py of the homepage app:

from django import forms
from cardetails.models import Car

class CarForm(ModelForm):
    allCars = forms.ModelChoiceField(queryset=Car.objects.all())

Of the 3 dropdown boxes I have, the one for "make" looks like so in the html template of the home page:

                <span style="display:inline-block">
                <select class="form-control" id="make">
                    {% for car in allCars %}
                    <option>{{ car.make }}</option>
                    {% endfor %}
                </select>
                <label for="make" style="display:block">Make</label>
            </span>

The view for which is:

from django.shortcuts import render

    def index(request):
    return render(request, 'search/index.html')

However, nothing appears in the "make" dropdown box. What I want to do is have all of the makes, models, and trims of all the cars in the database be selectable using the dropdown boxes.

Upvotes: 1

Views: 13227

Answers (1)

Abz Rockers
Abz Rockers

Reputation: 338

you can get the pk or id of the selected car and pass it to the next view where you want your user would be:

In you template.html

<form method='post' action=''>
    <select class="form-control" id="make" name='selected_car'>
        {% for car in allCars %}
            <option value='{{car.id}}'>{{ car.make }}</option>
        {% endfor %}
    </select>
</form>

In you view.py

view for template.html
def allCars(request):
     .....your code here to get all car....
    if request.POST:
        car_id = request.POST['selected_car']
        redirect('name-url',car_id=car_id)


view for car_detail.html
def carDetails(request,car_id):
    selected_car = Car.objects.get(pk=car_id)
    context = {}
    template = 'car_detail.html'
    render(request, template, context)

Hope this will help you.

Upvotes: 7

Related Questions