I have a question that always gets me stuck in all the projects I start. I don't know exactly when to put certain data in the models and others in the forms.
The questions would be:
What is the models for? And what is the forms for? What data goes in the first, and what in the second?
What I had understood is that the models, the data is saved in the database, while the forms appear in the django admin.
Greetings to the whole community!
The
Model
s allow to define in an easy and fast way the tables of a database. They also provide a simple API to get and create data from those tables.The
ModelForm
s provide an interface for creating forms for the web (in HTML), from the fields that you have previously defined in the data model. This avoids duplicating the necessary code, since the fields have already been defined for the database.For example, we have the following data model for an author:
Now we could create a
ModelForm
from the model to later create a form:Finally you can now manage the forms in your view, for example:
The object
form
can be passed to the template and it creates an HTML form automatically:For more information you can consult the documentation .
What is the models for?
The function of the models.py file is to operate as if it were a database using the OOP methodology , an acronym for Object Oriented Programming (if you did not configure the Settings.py file by default, it will use SQLite)
What data goes in the first, and what in the second?
If I didn't misunderstand your question, the frequently used data in the first models.py question is Classes, Methods and Attributes.
A simple example would be:
this is a simple help/guide on my part, it may not help much but at least it would give you an idea of how it would be used... your question is very concise you should look in the Django documentation, I recommend it, it is very complete and good done.