Skip to content Skip to sidebar Skip to footer

Form's Clean Method Not Getting Called

I am trying to create some objects with django's CBV FormView the code for form_class is like this: class UrlForm(forms.Form): url = forms.CharField(required=True,

Solution 1:

your post method is wrong. you must either use form_valid method like below

def form_valid(self, form):
    url = Url.objects.create(url= form.cleaned_data['url'])
    seo = Seo.objects.create(
                title = form.cleaned_data['title'],
                description = form.cleaned_data['description'],
                keywords = form.cleaned_data['keywords'],
                content_object=url)

    return redirect(self.get_success_url())

or if you want to use Post method use it like below:

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
        url = Url.objects.create(url= form.cleaned_data['url'])
        seo = Seo.objects.create(
                title = form.cleaned_data['title'],
                description = form.cleaned_data['description'],
                keywords = form.cleaned_data['keywords'],
                content_object=url)

    return redirect(self.get_success_url())

I'vent tested the code but it will work. Let me explain why your code didnt worked. In your post method you didnt initialized the form with post arguments. once the form is initialized you can run clean method and it will raise exceptions if any. Also since you are using FormView, there is a form_valid method (my recommendation is to first read before development). Another advice, since you are using form to create object, why not use CreateView and ModelForm.. :)

Solution 2:

This won't work because you're overriding entire post method in view. That post method is by default responsible for calling validation on form and calling form_valid or form_invalid method after that.

What is the point of using FormView if you're not using form at all.

Also: you sholud refer to form's cleaned_data instead of request.POST. It will contain only fully cleaned data.

Solution 3:

When calling clean you have to return clean data with self

defclean(self):
    url = self.cleaned_data.get('url')
    try:
        my_url = Url.objects.get(url=url)
        if my_url:
            raise forms.ValidationError("Seo Url already exists.")
    except Url.DoesNotExist:
        passreturn self.cleaned_data

Post a Comment for "Form's Clean Method Not Getting Called"