Published: Jan. 26, 2021 by lukemakin |  estimated reading time: 19 minutes
Dependent dropdown list in django and javascript
Source code to the video tutorial: How to create dependent dropdown lists with django, javascript + ajax & semantic ui framework

Dependent dropdown lists in Django with Javascript (+ ajax) and Semantic ui framework. In this video tutorial we are going to improve user experience by creating dynamic and depended dropdown lists to submit the form using ajax and create a car order in the database




base.html

{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<!-- semantic UI -->
<link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>

<!-- custom css & js -->
<script src={% static 'main.js' %} defer></script>
<script src={% static 'semantic.js' %} defer></script>
<link rel="stylesheet" href={% static 'style.css' %}>

<title>oder a car</title>
</head>
<body>
<div class="ui container mt-5">
{% block content %}
{% endblock content %}
</div>

</body>
</html>

cars  / models.py


from django.db import models

class Car(models.Model):
name = models.CharField(max_length=80)
country = models.CharField(max_length=100)

def __str__(self):
return str(self.name)

models / models.py


from django.db import models
from cars.models import Car

class Model(models.Model):
name = models.CharField(max_length=50)
car = models.ForeignKey(Car, on_delete=models.CASCADE)

def __str__(self):
return f"{self.car}-{self.name}"

orders / models.py


from django.db import models
from cars.models import Car
from models.models import Model

class Order(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE)
model = models.ForeignKey(Model, on_delete=models.CASCADE)

def __str__(self):
return str(self.pk)

orders / views.py


from django.shortcuts import render
from cars.models import Car
from models.models import Model
from .models import Order
from django.http import JsonResponse

def main_view(request):
qs = Car.objects.all()
return render(request, 'orders/main.html', {'qs':qs})

def traditional_view(request):
qs1 = Car.objects.all()
qs2 = Model.objects.all()
return render(request, 'orders/t.html', {'qs1':qs1, 'qs2':qs2})

def get_json_car_data(request):
qs_val = list(Car.objects.values())
return JsonResponse({'data':qs_val})

def get_json_model_data(request, *args, **kwargs):
selected_car = kwargs.get('car')
obj_models = list(Model.objects.filter(car__name=selected_car).values())
return JsonResponse({'data':obj_models})

def create_order(request):
if request.is_ajax():
car = request.POST.get('car')
car_obj = Car.objects.get(name=car)
model = request.POST.get('model')
model_obj = Model.objects.get(name=model, car__name=car_obj.name)
Order.objects.create(car=car_obj, model=model_obj)
return JsonResponse({'created': True})
return JsonResponse({'created': False})

orders / urls.py


from django.urls import path
from .views import (
main_view,
get_json_car_data,
get_json_model_data,
create_order,
traditional_view
)

app_name = "orders"

urlpatterns = [
path('', main_view, name='main-view'),
path('t/', traditional_view, name='t-view'),
path('cars-json/', get_json_car_data, name='cars-json'),
path('models-json/<str:car>/', get_json_model_data, name='models-json'),
path('create/', create_order, name='create-order'),
]

main urls.py


from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('orders.urls', namespace='orders')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

static / main.js


const carForm = document.getElementById('car-form')
const carsDataBox = document.getElementById('cars-data-box')
const carInput = document.getElementById('cars')
const modelsDataBox = document.getElementById('models-data-box')
const modelInput = document.getElementById('models')
const btnBox = document.getElementById('btn-box')
const alertBox = document.getElementById('alert-box')
const modelText = document.getElementById('model-text')
const carText = document.getElementById('car-text')
const csrf = document.getElementsByName('csrfmiddlewaretoken')

$.ajax({
type: 'GET',
url: '/cars-json/',
success: function(response){
console.log(response.data)
const carsData = response.data
carsData.map(item=>{
const option = document.createElement('div')
option.textContent = item.name
option.setAttribute('class', 'item')
option.setAttribute('data-value', item.name)
carsDataBox.appendChild(option)
})
},
error: function(error){
console.log(error)
}
})

carInput.addEventListener('change', e=>{
console.log(e.target.value)
const selectedCar = e.target.value

alertBox.innerHTML=""
modelsDataBox.innerHTML = ""
modelText.textContent = "Choose a model"
modelText.classList.add("default")


$.ajax({
type: 'GET',
url: `models-json/${selectedCar}/`,
success: function(response){
console.log(response.data)
const modelsData = response.data
modelsData.map(item=>{
const option = document.createElement('div')
option.textContent = item.name
option.setAttribute('class', 'item')
option.setAttribute('data-value', item.name)
modelsDataBox.appendChild(option)
})

modelInput.addEventListener('change', e=>{
btnBox.classList.remove('not-visible')
})
},
error: function(error){
console.log(error)
}
})
})

carForm.addEventListener('submit', e=>{
e.preventDefault()
console.log('submitted')

$.ajax({
type: 'POST',
url: '/create/',
data: {
'csrfmiddlewaretoken': csrf[0].value,
'car': carText.textContent,
'model': modelText.textContent,
},
success: function(response){
console.log(response)
alertBox.innerHTML = `<div class="ui positive message">
<div class="header">
Success
</div>
<p>Your order has been placed</p>
</div>`
},
error: function(error){
console.log(error)
alertBox.innerHTML = `<div class="ui negative message">
<div class="header">
Ops
</div>
<p>Something went wrong</p>
</div>`
}
})
})

static / semantic.js


$('.ui.dropdown').dropdown({
forceSelection: false
});







 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com