开发者

Django - partially validating form

开发者 https://www.devze.com 2022-12-29 11:07 出处:网络
I\'m new to Django, trying to process some forms. I have this form for entering information (creating a new ad) in one template:

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开发者_如何学C_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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消