Django - partially validating form

Posted by aeter on Stack Overflow See other posts from Stack Overflow or by aeter
Published on 2010-05-09T07:45:07Z Indexed on 2010/05/09 7:48 UTC
Read the original article Hit count: 200

Filed under:
|
|

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)
    ...

I validate it with "is_valid()" just fine.

Basically for the second validation (another template) I want to validate only against "category" and "sub_category":

In another template, 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. How can I validate only the 2 fields category and sub_category?

© Stack Overflow or respective owner

Related posts about django

Related posts about python