What is the use of forms.py in django

I just started learning django. And when I launched a small login system, I had to develop a form for it. I used an html page for this and processed the data in views.py and then put the answer in another view. But in the above examples, I came across some file called forms.py . I do not understand how to use it, which is easy to use and better to use between. Can someone help me?

+4
source share
2 answers

forms.py (e.g. admin.py ) is just the convention django uses. This is considered best practice, but not a strict requirement. There is nothing special or exotic in these files.

forms.py - where django documentation recommends placing all your forms; make your code easy to repair. Also, since its convention is mentioned in the documentation, it helps when you collaborate with others, because that is where others will look for your code related to forms.

Think of it as index.html . There is no rule indicating that this file should be called index.html , but it is an agreement that has been built over time.

You can use all form classes in your views.py and nothing will break. Now, if you do not use forms at all and still process the GET and POST data manually, you should stop it immediately; especially if it's more than a search query string.

The only file that is absolutely necessary is models.py .

+9
source

Creating models and views is "stupid" of choice: if you use a specific file like "form.py", where you have form classes along with their validations, it is much easier and especially faster to unit test these forms than using the Django test client. The same goes for models: any complex algorithms are usually included in the "utils.py" file (or similarly named), so this can be easier tested.

And finally, when the size of your views.py or models.py file gets bigger and bigger over time, it's a little annoying to constantly scroll through the file.

0
source

Source: https://habr.com/ru/post/1495107/


All Articles