I'm new to Django, trying to process some forms. I have this form for entering information (creating a new ad) in one template:
class Ad(models.Model):
...
category = models.CharField("Category",max_length=30, choices=CATEGORIES)
sub_category = models.CharField("Subcategory",max_length=4, choices=SUBCATEGORIES)
location = models.CharField("Location",max_length=30, blank=True)
title = models.CharField("Title",max_length=50)
...
-----------------------------------
class AdForm(forms.ModelForm):
class Meta:
model = Ad
...
I validate it with "is_valid()" and all is fine.
Basically for the second validation (another template) I want to validate only against "category" and "sub_category":
In another template (with another method from views.py), I want to use 2 fields from the same form ("category" and "sub_category") for filtering information - and now the "is_valid()" method would not work correctly, cause it validates the entire form, and I need to validate only 2 fields. I have tried with the following:
...
if request.method == 'POST': # If a filter for data has been submitted:
form = AdForm(request.POST)
try:
form = form.clean()
category = form.category
sub_category = form.sub_category
latest_ads_list = Ad.objects.filter(category=category)
except ValidationError:
latest_ads_list = Ad.objects.all().order_by('pub_date')
else:
latest_ads_list = Ad.objects.all().order_by('pub_date')
form = AdForm()
...
but it doesn't work.
EDIT: Solved it by adding:
class FilterForm(forms.ModelForm):
class Meta:
model = Ad
fields = ('category', 'sub_category')
and validating this form with "is_valid()" etc., which worked just fine.