Monday, March 18, 2024

Unable to get a simple two level dependent dropdown working

Can someone help me understand what am I doing wrong in this django dependent dropdown code? My selection for the first dropdown menu is one of ("NetEng", "ITDE") and when I select, let's say "NetEng", an ajax call is made to the ajax function in the backend views.py code, but a [] response is received. Ideally, I am expecting the value associated with "NetEng" or "ITDE" to be a response.

My forms.py:

from django import forms
from .models import TeamJira, TypeJira

class DropdownForm(forms.Form):
category = forms.ModelChoiceField(queryset=TeamJira.objects.all())
subcategory = forms.ModelChoiceField(queryset=TypeJira.objects.none())

def __init__(self, *args, **kwargs):
super(DropdownForm, self).__init__(*args, **kwargs)
self.fields['subcategory'].queryset = TypeJira.objects.none()
if 'category' in self.data:
try:
category_id = int(self.data.get('category'))
self.fields['subcategory'].queryset = TypeJira.objects.filter(category_id=category_id).order_by('name')
except (ValueError, TypeError):
pass
elif self.pk:
self.fields['subcategory'].queryset = self.instance.category.typejira_set.order_by('name')


My models.py

class TeamJira(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
return self.name

class TypeJira(models.Model):
category = models.ForeignKey(TeamJira, on_delete=models.CASCADE)
name = models.CharField(max_length=100)

def __str__(self):
return self.name
TEAM_CHOICE = (
('NetEng', 'NetEng'),
('ITDE', 'ITDE'),
)
class JiraAutomation(models.Model):
name = models.CharField(max_length=255, null=True, blank=True, default=None)
team_type = models.CharField(max_length=100, null=True, blank=True, default=None, choices=TEAM_CHOICE) # Change to CharField
ticket_type = models.CharField(max_length=255, null=True, blank=True, default=None)
url = models.CharField(max_length=255, null=True, blank=True, default=None)
isbn_number = models.CharField(max_length=13)

def __str__(self):
return self.name




My views.py function for the dependent dropdown ajax query:

from .models import TypeJira
from django.http import JsonResponse

def load_subcategories(request):
category_id = request.GET.get('category_id')
subcategories = TypeJira.objects.filter(category_id=category_id).values('id', 'name')
print("THIS IS SUBCATEG", subcategories)
print(list(subcategories))
return JsonResponse(list(subcategories), safe=False)
# return HttpResponse("hello")

Javascript function for ajax in the template:
<form method="post" id="dropdown-form">
{% csrf_token %}
{{ form.as_p }}
</form>
<script>
$(document).ready(function() {
$('select[name^="form-0-team_type"]').change(function() {
var categoryId = $(this).val();
$.ajax({
url: '/load_subcategories/',
data: {
'category_id': categoryId
},
dataType: 'json',
success: function(data) {
var subcategorySelect = $('select[name^="form-0-ticket_type"]');
subcategorySelect.empty();
$.each(data, function(index, subcategory) {
subcategorySelect.append($('<option>', {
value: subcategory.id,
text: subcategory.name
}));
});
}
});
});
});
</script>



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e3980053-5df1-414f-9024-87ccffe41b34n%40googlegroups.com.

No comments:

Post a Comment