Process of creating form in Django? - django

Django is really flexible. The simple html form can be used and processed in Django. But while going through the Django documentation I find that there are numerous ways to write a form in Django. The best I find is to create a forms.py and then create a template for it and process using views. Is this the right approach? I think it's way too easy to validate the form and use it in template using this approach. But I am confused where to apply the validation rules in this process. I want to use less Javascript as possible.

For validation you can specify them by
while defining field using validators attribute
by implementing clean_field() method in form
or clean() method in form for multiple field dependent validation.
The validation will be done when you call form.is_valid() method in the view where you are processing the form.
Here is more detailed documentation. Form and field validation

Related

Serializer Equivalent of clean for django forms in rest framework Serializers

What is the serializer equivalent of the clean method for django forms.
My use case is that I want to do custom model field validation of some fields for a model serializer class. My guess is it could be the run_validators, for the framework. But I am not sure with certainty.
Thanks,
Best regards,
Well, just gone through the documentation and the equivalent is validate (for object level validation). For field level validation use. validate_<field_name>'
See link for more details

django use ModelForm to validate a Model

Suppose I have a ModelForm for my Model with custom validation logic, and I want to reuse that to validate an existing model instance. Is there any way to do this?
I thought I could just do something like MyModelForm(instance=foo).is_valid(), but that doesn't work for multiple reasons.
I'd like to reuse the existing form validation to avoid duplication of code, but I can't find any way to do so.
Edit: I'm using Django 1.10, in case that makes a difference.

Do I need to create forms.py for my forms in Django?

I'm about to create a form in my website made in Django with elements that have complex input types from different plugins (like calendar plugins). Also, I'll be using a Validator plugin which validates the input before submission.
My question is do I need to create forms.py and like model the form or can I just create the form manually? The former seems like a very hassle process. Which one is more efficient and recommended?
As #dmitryro said you can create your forms manually in the templates and then getting in the request. It's recommended to use the forms api provided by Django since it allows you to reuse, validate, and customize your forms.
As to whether or not it is a good practice that depends completely on you but if you are trying to scale an application I would recommend use the forms.
It is good to use Django's built in form.
If we use django's form then we only have to write python code and django will create corresponding html for it. And our code will be short and clean.

When to use form vs model validation?

Just curious. What is the best practice for when to use form vs model validation?
From what I understand currently, form validation should be used for:
AJAX / HTTP requests params
Forms that do not correlate to a model?
Another question is: I have a HTML form that roughly correlates to a model instance, do I use a ModelForm for it?
Definitely use ModelForm, if your form resembles model object even in a tiny bit.
If there are some minor differences (e.g. you don't use some of the fields or you want to use different error messages etc.) it's much easier to customize ModelForm then to use Form and implement all this functionality from scratch.
For more reference regarding ModelForm please checkout PyDanny's Core Concepts of Django ModelForms.
I am also trying to understand what is the difference/relation between form and model validation and I would like to share my notes that are formed after reading several docs.
I am currently interested in Creating Forms from Models
#mariodev shared the document Core Concepts of Django ModelForms and this provided a good start.
ModelForms select validators based off of Model field definitions
The main story behind the scenes seems to be the DRY principal. This article explains very well what exactly is the case here.
All right, all this is fair. The question is "Where in the Django Documentation is this explained"?
I bumped on a very brilliant article where it states that:
The form.full_clean() method is called by django at the start of the validation process (by form.is_valid(), usually immediately after the view receives the posted data).
Correct me if I am wrong but that line reads that everytime I enter data and hit 'enter' the validation process begins!
OK, this is simple now:
The validation on a ModelForm begins when we hit 'enter'.
Django first validates the form by checking one by one every applicable validation method on Fields, Field Subclasses (This is the documentation for a model's field subclass, not for a form field subclass), Form Subclasses and ModelForm (since it is a ModelForm).
Finally, it validates the Model Instance.
This is how all this works theoretically. The only thing that remains is to implement it.

Separating form input and model validation in Django?

Is it typical to separate input validation from model-level validation in Django projects? For example, validating that a username fits naming criteria would be input validation, and verifying that the user isn't already in the database would be model-level validation.
I've been looking at a co-worker's code, and they put both types of validation in a form class (in forms.py). Is this the typical setup, or is it more common for the model-level validation to appear in the model or view?
Or is there a better way to be approaching this-- such as using a ModelForm? I'm rather new to Django and trying to learn what is the recommended pattern for this situation.
This is a very interesting question (for me).
In my opinion, all validation code should be moved to model code. This is the way to not break business rules. When validation code is in the model it is not possible to forget some validation in a new form or to have inconsistent rules in several forms.
I link to you 'Django, Raise a validation error in a model's save method' question that is related to yours. Below question you can see how move code validations from forms to model. I hope that this brief introduction can helps to you.
From what framework you come? How validation rules are writen in your enviromnent?
I don't agree with the accepted answer. I prefer to use model-level validation to avoid inconsistencies in models, and form-level validation for any site-specific restrictions.
Suppose we have a model for events, with datetime fields for the start and end time. Model validation would force us to have an end time that comes after the start time. However, I would leave it in the form to validate that the newly created event is not in the past. Therefore, if I ever have to add an event that occured in the past, I could use an admin-specific form that allows dates in the past, or simply add it straight to the database.
Thus, model validation should only check for values that are patently wrong. but if you ever need to do something funky (Unicode characters in a username for a bot, for example), it should let you do it, even if it's only through the admin or the shell. I've read an answer on StackOverflow that suggested always using forms in backend code, filling fields with code like form["field"] = "value", to benefit from consistent validation.