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.
- Password validation in Python
- Python | Django News App
- Django URL patterns | Python
- Views In Django | Python
- Django Migrations | Python
- Name validation using IGNORECASE in Python Regex
- Python | Uploading images in Django
- Python | Sessions framework using django
- Intermediate fields in Django | Python
- Python | Django Admin Interface
- Python | ToDo webapp using Django
- Python | Extending and customizing django-allauth
- Python | Relational fields in Django models
- Python | Django-allauth setup and Configuration
- Python | User groups with Custom permissions in Django
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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