user1807271
user1807271

Reputation: 1006

Django: If I call is_valid() on a form do I still have to clean the data in forms.py?

If I call is_valid() on a form do I still have to clean the data in forms.py? I feel like it is redundant. I know that is_valid() is suppose run clean() automatically, so why would the framework let the user use the clean() function in forms.py?

forms.py

from django.core.validators import RegexValidator
my_validator = RegexValidator("\d{6}\-\d{2}", "CAPA format needs to be ######-##.")

class IncidentSearchForm(forms.Form):

    id = forms.IntegerField(required=False)
    user_id = forms.ModelChoiceField(User.objects.all(), required=False) 
    capa = forms.CharField(
        label="CAPA",
        required=False,
        validators=[my_validator]
        )

    def search(self):

        id = self.cleaned_data.get('id')
        user_id = self.cleaned_data.get('user_id')
        capa = self.cleaned_data.get('capa', None)

        if id is not None:
            query = query.filter(id=id))
        if user_id is not None:
            query = query.filter(user_id=user_id)
        if capa is not '':
            query = query.filter(capa=capa)

        return(query)

view.py

@login_required(login_url='/login/')
def index(request):

    template = "index.html"
    form = IncidentSearchForm(request.GET) # or None
    incident_list = None

    if form.is_valid():
        incident_list = form.search()
        context = { "form": form,                       
                    "incident_list": incident_list}
        return render(request, template, context)

    else:
        # form is empty show all OPEN incidents
        form = IncidentSearchForm()
        incident_list = Incident.objects.filter(open = 'True').order_by('-incident_date_time_reported')
        context = { "form": form,
                    "incident_list": incident_list}
        return render(request, template, context)

Upvotes: 0

Views: 811

Answers (1)

Tom
Tom

Reputation: 22841

is_valid() checks the form's errors property which (assuming it hasn't already been run) calls full_clean() which calls _clean_form() which calls clean() so there is no need to call the method directly.

keep feeling like self.cleaned_data.get is redundant because I call is_valid() in views.py

I'm not 100% sure on your objection, but note that cleaned_data will be empty unless clean() completes successfully, so your search function won't work properly without the check. You are correct that you shouldn't need to use get there for any required fields, but since you don't have required fields it's still a better bet.

Upvotes: 1

Related Questions