Dear all,
I'm very unexperienced with Django but at the same time I'm trying hard to learn as much as possible.
In my website I have a form with two dropdown menus, and I'd like to make the second (items) dependent by the first (categories).
As an example, in the first dropdown the possible choices are FRUITS and VEGETABLES.
When the user selects FRUITS, I'd like the second dropdown to show only ORANGE, APPLE, PEAR, etc.
Else, when the user selects VEGETABLES, I'd like the second dropdown to show only LETTUCE, CABBAGE, CARROT, etc
My current code follows (I kept it simple): the form shows two independent dropdown menus.
Unfortunately I've not been able to adjust it as requested by django-smart-selects, e.g. by correctly modifying the Item model and the forms.py file.
Could anyone help me, please?
*********************************************
The choices are stored in a MySQL database in two tables:
Types
ID Name
1 FRUIT
2 VEGETABLE
Items
ID Type_ID Name
1 1 Orange
2 1 Apple
3 1 Pear
4 2 Lettuce
5 2 Cabbage
6 2 Carrot
Each item is therefore associated to a unique type (fruit or vegetable).
*********************************************
My models.py consists of:
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
class Type(models.Model):
name = models.CharField(max_length=20)
class Item(models.Model):
name = models.CharField(max_length=20)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
*********************************************
My forms.py is:
from django import forms
from .models import Type, Item
class SelectForm(forms.Form):
q = Type.objects.all()
qf = forms.ModelChoiceField(queryset = q, empty_label = None)
s = Item.objects.all()
sf = forms.ModelChoiceField(queryset = s, empty_label = None)
*********************************************
My views.py is:
from django.shortcuts import render
from .forms import SelectForm
def index(request):
form = SelectForm()
context = {'f': form}
return render(request, 'selects/test.html', context)
*********************************************
Finally, my template is:
<html>
<head>
<title>Select data</title>
</head>
<body>
<form action="/show_results/" method="get">
{{f.as_p}}
<input type="submit" value="Submit">
</form>
</body>
</html>