Pull select form options from database in Django -
i'm making simple 2-page website allow user use dropdown boxes or html select forms (make, model, trim) on front page information car stored in database. after pressing search button, user taken page provides information vehicle. i'm confused how go linking these dropdown boxes data database in django.
the car model have resides in models.py of cardetails app , looks 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 actual name of car instead of "model-object" def __str__(self): return self.make + " " + self.model + " " + self.trim
googling led me way of setting modelform, resides in forms.py of homepage app:
from django import forms cardetails.models import car class carform(modelform): allcars = forms.modelchoicefield(queryset=car.objects.all())
of 3 dropdown boxes have, 1 "make" looks in html template of home page:
<span style="display:inline-block"> <select class="form-control" id="make"> {% car in allcars %} <option>{{ car.make }}</option> {% endfor %} </select> <label for="make" style="display:block">make</label> </span>
the view is:
from django.shortcuts import render def index(request): return render(request, 'search/index.html')
however, nothing appears in "make" dropdown box. want have of makes, models, , trims of cars in database selectable using dropdown boxes.
you can pk or id of selected car , pass next view want user be:
in template.html
<form method='post' action=''> <select class="form-control" id="make" name='selected_car'> {% car in allcars %} <option value='{{car.id}}'>{{ car.make }}</option> {% endfor %} </select> </form>
view template.htmlin view.py
def allcars(request): .....your code here car.... if request.post: car_id = request.post['selected_car'] redirect('name-url',car_id=car_id)
def cardetails(request,car_id): selected_car = car.objects.get(pk=car_id) context = {} template = 'car_detail.html' render(request, template, context)
hope you.
Comments
Post a Comment