Validations in Class Based View ... form_valid or form_invalid


There is something I do not understand when making validations in class-based views ( CreateView , UpdateView , etc), I understand that you can do with the method form_valid and then save it with a simple

But what if I want to enter an element within that form, such as username of a user or email , also things like checking if a title already exists or a url was added before that the form be sent.

How could I do that?

Are those variables stored in form.cleaned_data[variable] ?

If someone can help me with this, I'll appreciate it.

asked by ikenshu 05.09.2017 в 14:35

2 answers

def form_valid(self, form):
    form.instance.created_by = self.request.user
    return super(AuthorCreate, self).form_valid(form)

As you see in this example, the best way is to pass the form through the function and with the instance parameter we add the field that we want to modify. In your case it would be the same, only that instead of created_by it replaces by username or by the field of your case.

If your class did not define form, likewise you put it, django already knows which form is being manipulated. Remember to manipulate the super with the name of your class

answered by 08.09.2017 / 17:32

The CreateView, UpdateView, DeleteView views have one variable in common:


This variable stores "instance / object" that you are manipulating in the form. Note that every time you save the form in these views except for DeleteView, form_valid saves the changes and that new instance stores it in self.object.

self.object =
answered by 06.09.2017 в 22:15