I encountered with problem that my subcategory does not show proper data according to it is related category
This is models.py
class Category(models.Model):
category_name=models.CharField(max_length=100,unique=True,null=False)
def __str__(self):
return self.category_name
class Subcategory(models.Model):
category=models.ForeignKey(Category,on_delete=models.CASCADE)
subcategory_name=models.CharField(max_length=100,null=False)
This is forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Ad,Photo,Subcategory,Category
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError("This email is already taken.")
return email
class AdForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label=None)
subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.none())
class Meta:
model = Ad
fields = ['title', 'description', 'category', 'subcategory', 'price', 'location']
This is my views.py
def publish_ad(request):
if request.method == 'POST':
form = AdForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('index') # Redirect to a success page or any other URL
else:
form = AdForm()
return render(request, 'market/publish_ad.html', {'form': form})
This is a html file
{% extends "market/base.html" %}
{% load static %}
<!-- publish_ad.html -->
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Publish Ad</button>
</form>
{% endblock content %}
I tried different techniques but none of them did not work. Should i change something in my forms.py or I can change my html file?
Welcome @JasurAkhmedoff !
Are you trying to update the list of subcategories when something is selected for category? If so, what you’re looking for is called either “chained” or “cascade” select fields. There are a lot of topics here in the forum discussing it.