How to create a dropdown in forms in django with values from database
I'm trying to create a form with a drop down box where the user can select the location from the pre-exsiting locations in table.Stuck on what to do
forms.py
from django import forms
from .models import Vehicles
from .models import HomeLocation
class VehicleForm(forms.ModelForm):
HomeLocation= forms.ModelChoiceField (queryset=HomeLocation.objects.all(),
empty_label="Select a home location" # Optional
)
class Meta:
model = Vehicles
feilds=['home_location','model','make','year']
exclude = ['Location lat', 'Location long']
model.py
from django.db import models
class HomeLocation(models.Model):
home_location_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
class Vehicles(models.Model):
vehicle_id = models.AutoField(primary_key=True)
home_location = models.ForeignKey(HomeLocation, models.DO_NOTHING)
model = models.CharField(max_length=255)
make = models.CharField(max_length=255)
year = models.IntegerField()
views.py
from django.shortcuts import render
from .models import Vehicles
from .models import HomeLocation
from .forms import VehicleForm
from django.contrib import messages
from django.http import HttpResponse
# Create your views here.
def addVehicle(request):
if request.method =="POST":
form = VehicleForm(request.POST or None)
if form.is_valid():
form.save()
messages.success(request,("Vehicle has been added successfully"))
else:
return render(request,'add_vehicle.html',{})
add_vehicle.html
<form method="POST" action= "{% url 'addVehicle' %}">
{% csrf_token %}
<div class="form-header">
<h1>Add Vehicle</h1>
</div>
<div class="form-group">
<div class="mb-3">
<select>
{% for i in HomeLocation %}
<option value="{{ i.home_location_id }}"> {{ i.name }} </option>
{% endfor %}
</select>
</div></div>
This is what I have done so far. But no data can be seen in dropdown as seen. What do I need to do.
in its simplest form this is what you would want to do
In your forms.py file
class VehicleForm(forms.ModelForm):
class Meta:
model = Vehicles
fields = ['home_location ','model','make','year',]
required = ('home_location ','model','make','year',)
in your views.py:
if request.method =='POST':
form = VehicleForm(request.POST)
if form.is_valid():
form.save()
return redirect('<your success redirect link>')
form=VehicleForm()
context = {'form': form,}
return render(request, '<path-to add_vehicle.html>',context)
in your template:
<form method="POST" action= "">
{% csrf_token %}
<div class="form-header">
<h1>Add Vehicle</h1>
</div>
<div class="form-group">
<div class="mb-3">
{{form}}
</div></div>
few more items:
you don't need these fields in your models: home_location_id and vehicle_id
these fields will be generated automatically and can be referenced as <object>.id