Django works on a MVC pattern. So there is a need to create data models (or tables). For every table a model class is created. Some of the advantages of a MVC framework are listed out here.
Suppose there is a form which takes Username, gender and text as input from user, the task is to validate the data and save it.
In django this can be done, as follows:
After creating the data models, the changes need to be reflected in the database to do this run the following command:
python manange.py makemigrations
Doing this compiles the models and if it didn’t find any errors then, it creates a file in the migration folder. Later run the command given below to finally reflect the changes saved onto the migration file onto the database.
python manage.py migrate
Now a form can be created. Suppose that the username length should not be less than 5 and post length should be greater than 10. Then we define the Class PostForm with the required validation rules as follows:
Till now, the data models and the Form class are defined. Now the focus will be on how these modules, defined above, are actually used.
First run the localhost through this command
python manage.py runserver
Open http://localhost:8000/ in the browser, then it’s going to search in the urls.py file, looking for ‘ ‘ path
urls.py file is as given below:
Basically, this associates the ‘ ‘ url with a function home which is defined in views.py file.
home.html template file
Opening http://localhost:8000/ in the browser shows the following,
If a form with username of length less than 5 is submitted, it gives an error at the time of submission and similarly for the Post Text filled as well. The following image shows how the form behaves on submitting in valid form data.
- required - Django Form Field Validation
- initial – Django Form Field Validation
- label – Django Form Field Validation
- label_suffix - Django Form Field Validation
- error_messages - Django Form Field Validation
- help_text - Django Form Field Validation
- disabled - Django Form Field Validation
- help_text - Django Built-in Field Validation
- error_messages - Django Built-in Field Validation
- primary_key - Django Built-in Field Validation
- default - Django Built-in Field Validation
- verbose_name - Django Built-in Field Validation
- editable=False - Django Built-in Field Validation
- unique=True - Django Built-in Field Validation
- blank=True - Django Built-in Field Validation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai