views:

52

answers:

1

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.

+1  A: 

Have you tried subclassing AdForm and modifying the fields in the inner Meta class? Something like this:

class AdFormLite(AdForm):
    class Meta:
        fields = ['category', 'sub_category']

From the documentation for ModelForm on changing the order of fields:

The fields attribute defines the subset of model fields that will be rendered, and the order in which they will be rendered.will be rendered.

jathanism
I have solved it in a way very much similar to the way you described it - it's just that I have subclassed the ModelForm instead of AdForm. Upvoting your answer and accepting it as correct, as the solution I have is almost the same :)
aeter
Excellent, I am happy this what you were looking for!
jathanism