Django rest framework Part 1 : Custom User model
Django comes with a built-in User model for authentication. However, the official Django documentation recommends using custom user model. In this tutorial we will create a project with a custom user model.
Grab the code here
Set up the project
To start, In your local computer, do the following:
$ mkdir blog
$ cd blog
$ pipenv shell
$ pipenv install django
pipenv shell is a command to create and activate virtual environment.
Open the working directory using your favorite IDE
Create a project
Create a Django project using the following command. We will name our project app
django-admin startproject app
This is our current directory structure
Directory structure
Lets do some clean up in our directory structure. This will eliminate the need of navigating to app folder to start the server.
We are going to move all the files inside app/app/
to app/
use this command mv app/app/* app
and move manage.py
to the top of our directory structure using mv app/manage.py .
Now delete the app
folder inside the app
using this command rm -rf app/app
This is what our project structure should look like.
Run python manage.py runserver to start the server. Visit this link http://127.0.0.1:8000/ and you should see the Django welcome screen.
Create API app
Inside app folder, run
django-admin startapp authentication
You will notice an authentication folder has been created inside app folder and inside authentication there are a couple of files.
Register the authentication app with the app project
So we edit app/settings.py under INSTALLED_APPS
INSTALLED_APPS = [
...
'app.authentication',
...
]
Database connection
We are using PostgreSQL database. We will need to install psycopg2 which is the most popular PostgreSQL database adapter for the Python programming.
pipenv install psycopg2
Create a database and give it the name of your choice, I named mine blog. Create a .env file to store the environment variables.
export DB_NAME=<your_db_name>
export DB_USER=<your_db_user>
export DB_HOST=localhost
export DB_PASSWORD=<your_db_password>
Run source .env
to set the environment variables. Then we edit app/settings.py under DATABASES as follows.
Ensure you
import os
at the top of settings.py
We are not going to run
python manage.py migrate
at this point. It's important to wait until we have created our new custom User model.
Creating Models
Navigate in app/authentication/models.py and add the following code. This will override the built in User model.
Then in app/settings.py , lets override the default user model by providing a value for the AUTH_USER_MODEL referencing our custom model
...
AUTH_USER_MODEL = 'authentication.User'
...
Make migrations
Whenever we define or change a model, we need to tell Django to migrate those changes
$ python manage.py makemigrations Migrations for 'authentication':
app/authentication/migrations/0001_initial.py
- Create model User$python manage.py migrateOperations to perform:
Apply all migrations: admin, auth, authentication, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying authentication.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying sessions.0001_initial... OK
Serialize the User model
Now we’re starting to get into some Restful concepts. We need to tell REST Framework about our User model and how it should serialize the data. Serialization is the process of converting a Model to JSON.
Run pipenv install djangorestframework
to install django rest framewok. Open the app/settings.py under INSTALLED_APPS and add rest_framework
INSTALLED_APPS = [
...
'rest_framework',
...
]
The serializer will convert the user model instance to JSON representation. In turn when the user post JSON data to our api, the serializer will convert it to User model instance in order for us to save.
So create app/authentication/serializers.py and edit it as follows
Display the data(Views)
We need to receive http request with JSON data via our api and save it to our User model. Write the following code in app/authentication/views.py
Handling Urls
We’ll specify URLs as endpoints for consuming our API. Create a app/authentication/urls.py this is where we are going to define our url patterns.
Finally we add a url to the main app’s urls.py file so that it points to our API app. Open app/urls.py
Project structure
Our final directory structure should be like the following
Finally! Lets run
$ python manage.py runserverWatching for file changes with StatReloader
Performing system checks…System check identified no issues (0 silenced).
February 20, 2021–09:05:08
Django version 3.1.5, using settings ‘app.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Navigate to http://127.0.0.1:8000/auth/signup/ .Yeeah!! it works