I am trying to use here Django dependent dropdown list. But at the same time, the error occurred. If I make an ajax request click the product category and the dependent dropdown not working togetherly and cannot make an ajax request shows an error. How to resolve this error? Can please someone help me to clear this issue.
Models.py
from django.db import models
class ProductCategory(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class SubCategory(models.Model):
country = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Vendor(models.Model):
designer_name = models.CharField(max_length=100, default='')
design_name = models.CharField(max_length=200)
description = models.TextField(max_length=5000)
productcategory = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL,
null=True)
subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.designer_name
forms.py
from django import forms
from .models import Vendor, ProductCategory, SubCategory
class DesignerForm(forms.ModelForm):
class Meta:
model = Vendor
descr = forms.CharField( widget=forms.Textarea )
fields = ('designer_name','design_name', 'description', 'productcategory', 'subcategory')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['subcategory'].queryset = SubCategory.objects.none()
if 'productcategory' in self.data:
try:
productcategory_id = int(self.data.get('productcategory'))
self.fields['subcategory'].queryset = SubCategory.objects.filter(productcategory_id=productcategory_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['subcategory'].queryset = self.instance.productcategory.subcategory_set.order_by('name')
Views.py
from .models import *
from django.shortcuts import render, redirect
from .forms import *
def Products(request):
if request.method == 'POST':
form = DesignerForm(request.POST)
if form.is_valid():
form.save()
return redirect('Products')
else:
form = DesignerForm()
return render(request, 'jinja2/products.jinja',{'form': form})
def ajax_load_subcategories(request):
productcategory_id = request.GET.get('productcategory')
subcategories =
SubCategory.objects.filter(productcategory_id=productcategory_id).order_by('name')
return render(request, 'jinja2/city_dropdown_list_options.jinja', {'subcategories':
subcategories})
admin.py
from django.contrib import admin
from boutique_store.models import Vendor, ProductCategory, SubCategory
# Register your models here.
admin.site.register(ProductCategory)
admin.site.register(SubCategory)
admin.site.register(Vendor)
urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('add/', views.Products, name='Products'),
path('ajax/load_subcategories/', views.ajax_load_subcategories,
name='ajax_load_subcategories'), # <-- this one here
]
products.jinja
{% block content %}
<h2>Person Form</h2>
<form method="post" id="designerForm" data-subcategories-url="{% URL
'ajax_load_subcategories' %}" novalidate>
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<button type="submit">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous">
</script>
<script>
$("#id_productcategory").change(function () {
var url = $("#designerForm").attr("data-subcategories-url");
var productcategoryId = $(this).val();
$.ajax({
url: URL,
data: {
'productcategory': productcategoryId
},
success: function (data) {
$("#id_subcategory").html(data);
}
});
});
</script>
{% endblock %}
city_dropdown_list_options.jinja
<option value="">---------</option>
{% for subcategory in subcategories %}
<option value="{{ subcategory.pk }}">{{ subcategory.name }}</option>
{% endfor %}
CodePudding user response:
In SubCategory
model you have a field named country
which refers to ProductCategory
. You can't filter with productcategory_id
because there is no such column/field in current model.
class SubCategory(models.Model):
country = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
So try to fix your queries like below in forms.py
and views.py
:
SubCategory.objects.filter(country_id=productcategory_id).order_by('name')