Creating a User Model
Learn about Django models and how to create a user model for a web application with user registration and login features.
We'll cover the following
Unless we are creating a simple web application, there is little chance of avoiding the necessity to interact with a database, particularly if we have an account feature that requires users to register or login to use our web application.
Before talking about the account feature, let’s learn more about Django models and what problems they resolve.
What are Django models?
If we need to connect our application to a database, particularly SQL, the first assumption that comes to mind is that we’ll have to work directly with the database via SQL queries. If that’s true, it can be fun, but it’s not the same for everyone; some developers may find SQL complex. We are no longer focusing on writing the application logic in our own language. Some tasks can become repetitive, such as writing SQL scripts to create tables, getting entries from the database, or inserting or updating data.
As we’ll see, the more the code base evolves, the more difficult it becomes to maintain both simple and complex SQL queries in our code base. This is more of an issue if we are working with multiple databases, which will require us to learn many SQL languages. For example, there are a lot of SQL databases, and each one implements SQL in its own way.
Fortunately, in Django, this messy issue is solved by using a Django model to access the database. This doesn’t mean that we don’t have to write SQL queries: it’s just that we don’t have to use SQL at all unless we want to.
Django models provide object-relational mapping (ORM) to the underlying database. ORM is a tool that simplifies database programming by providing a simple mapping between the object and the database. Then, we don’t necessarily need to know the database structure or write complex SQL queries to manipulate or retrieve data from the database.
For example, creating a table in SQL will require writing a long SQL query. Doing this in Python will just require writing a class inheriting from the django.db
package:
Get hands-on with 1200+ tech skills courses.