[Django]-Django form methods are for validation only or not?

1đź‘Ť

âś…

The first time I got the same weird feeling was when I encountered the LoginForm from django.contrib.auth that also verifies that the user’s browser is capable of working with cookies aside from managing the credentials passed in.

Personally, I agree with you. I’m more inclined to think that the view should be the responsible actor for performing the action of sending the email rather than the form and that send_email should be a method defined in the view.

But, then again, you can easily observe how a lot of us use Django differently or have a different approach to solving the same problems. Due to the fact that we have different concerns in mind when developing our applications, it’s quite possible we have a different understanding of how certain framework components are meant to be used, which is a bit of a moot point. In the end, what’s important to acknowledge is that it’s possible to delegate some of the heavy-lifting from the view to the form in a manner that’s well-defined.

4đź‘Ť

There is no correct answer for this one. It really depends on your coding style. Using a form for more than just validation is as valid as doing this method in the view.

The above example has some kind of advantage though. Lets say you have one model and you want to use different forms (with different logic) for it. Instead of putting the logic in the view and check which form is now used it probably better to put this logic on the form level.

1đź‘Ť

There is nothing wrong with the example. For any but the simplest of cases, your form will contain only cleaning methods; most forms do extra validation and other actions. In the end, it is just a Python class and you can do whatever you would like in it; there is no “rule” except maybe DRY.

We have form methods that validate against external services, call other procedures and trigger workflows. For such complicated logic, it is best to embed it in to the form class as it increases reusability of the code. Developers working on the view simply use the form class as a library and don’t have to worry about exotic validation requirements. In this case, it actually promotes DRY.

When we have to update the logic we only update the form class’s “private” methods (those prefixed with _). This keeps the “public” interface (documented by django) intact and all view code using that form doesn’t have to be updated.

👤Burhan Khalid

Leave a comment