Adding code to a Class

I have a simple class that I am using to add records to a database table.

class AddPickView(CreateView):
model = Pick
form_class = PickForm
template_name = ‘add_pick.html’

Is there a way to add code to this so I can perform checks on the data before saving it to the database?

It seems easier to do this using Functions instead of Classes.

Any help would be greatly appreciated.

You will have to do this within the PickForm class. You can add validation, or clean, methods to each field of your form and raise errors if the data does not suit your specific needs.

I have written applications using functions where I could do logic in the function before a form.save() event. But, I am not sure how to do that using a Class.

You want to make the appropriate decision as to where this logic belongs. (Just because you’ve put logic in your view function in the past doesn’t necessarily mean that it always belongs in the view.)

If the validation and logic is only related to the data within the form, then it’s likely to be more appropriate to put that logic within the form as described by @Suttonium above.

However, if you are performing validation of the form with data that exists outside the form, then you would want to override the appropriate method of your view class. You reference the CreateView in your snippet above, which means you could override the form_valid methon within that class.

See:

(Note: that last link is to the Classy Class-Based Views site - an invaluable resource for understanding how the built-in generic CBVs are put together. I recommend bookmarking the site and spending some time browsing through it if you really want to understand how the CBVs work. I also recommend the CBV Diagrams page.)