Django-Rest-Framework User CRUD functionality, Login and Logout

Chapi Menge
4 min readOct 25, 2021

Hello Everyone , My name is Chapi Menge. I am Python/Django Developer.

Today we will see

  1. how to do we Register , Update , View and Delete Users.
  2. How to Login and Logout Users with Token Authentication.

First of all i am considering all of you have some idea about Django and Django-Rest-Framework. So let’s dive in.

So let’s start by creating our project

django-admin startproject authentication # create the project cd authentication  # go to the project directorypython3 manage.py startapp accounts  # create django app 

So the first thing we will do is to register the Rest Framework app and our accounts app to our project settings.

INSTALLED_APPS = [
...
# 3rd party 'rest_framework', 'rest_framework.authtoken', # for token authentication # My apps 'accounts']

So after we add the rest_framework apps to our INSTALLED_APPS, we can now migrate our database by using

python manage.py migrate

This will create Django basic database model and Rest-framework Token model to our database.

Till now we accomplish very simple configurations. Now let’s star coding

So the first thing we should do is to create Serializer for our user model. so create a file called accounts/serializers.py and paste the code below.

So we override the create method to implement our logic before saving to our database. we can check a lot of things before saving to our databases. This kind of task can be done here or in our view but here is one option to do it.

Next We start writing our view for the User CRUD functionality using ViewSets. open your accounts/views.py and paste the code below

So here in the views, we override two methods. The first method is

def get_queryset(....):
....
....

The reason for overriding is to control the permission of the user when giving the list of users. So if the user is Superuser we can give every list of the user we have. Here if you notice we didn’t user Pagination to make things very simple but you might want to add if the User base you have is very large.

The Second method we override is

def get_object(self):
...

we override this method to make restriction for unauthorized access of user detail information. Unless you are superuser or it is your data you can’t access your data using their user id. Because we checked the object permission before we return the data.

Now we have Fully Functional User Registration, Update, Deletion and Detail View just using ViewSets.

So let’s register out URLs.

First let’s register the project URL to include our app URL configurations and patters.

by heading to authentication/urls.py and paste the code below.

urlpatterns = [    path('', include('rest_framework.urls')),    path('api/', include('accounts.urls')),]

we will add the restframework URLs and our app url to project URL patterns.

After that we will go to our app URL configurations and add some configurations too. create urls.py inside our accounts directory and paste the code below.

accounts/urls.py

# 3rd partyfrom rest_framework.authtoken import viewsfrom rest_framework.routers import DefaultRouter
# My apps importsfrom accounts.views import LogoutView, UserViewSet
router = DefaultRouter()router.register(r'users', UserViewSet, basename='users')
urlpatterns = [
path('', include(router.urls)),]

Now let’s start our server and open up the browser or POSTMAN to interact to our system.

python manage.py runserver

Go to http://localhost:8000/api/users and explore by creating(GET) , retrieving(GET api/users/<int:id>).

So next is to get the token to authorize our identity. this is already done by DRF and we will gonna use it now.

go to accounts/urls.py

urlpatterns = [   path('', include(router.urls)),
path('login', views.obtain_auth_token),
]

so using this /login endpoint we can obtain our token. So we will pass the username and password in POST request if it is correct it will give us the token we need.

POST /api/login{    "username":  "",
"password": ""
}

So after the above request we will get TOKEN for our authorization but before we will use this token we need to add TokenAuthentication class to DEFAULT_AUTHENTICATION_CLASSES in settings.

authentication/settings.py....
....
# Rest Framework settings
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ]}

This setting will add the token authentication to be included and recognized in the requests. After we added our token authentication we can now send a request by adding the token we had earlier.

So let’s start using it. if you remember when we finish USER CRUD functionality but we didn’t use Retrieve, Update and DELETE functionality. now is the time to use them because we can authenticate our self using TOKEN.

So in our POSTMAN we will set our HEADER to

Authorization: Token 9944b09199c..................

to the endpoint /api/users/1 we will get the first user information in JSON format.

Finally, we will build Logout View for deleting our token.

go to accounts/views.py

class LogoutView(APIView):  permission_classes = (permissions.IsAuthenticated,)  def post(self, request):
request.user.auth_token.delete()
return response.Response(status=status.HTTP_200_OK)

so this will delete our token and log out our session. we should add this view to our urls too right ?

go to accounts/urls.py

....urlpatterns=[
....
path('logout', LogoutView.as_view()),
]

Now we completed our GOAL which is to make

  1. User Registration
  2. User Deletion ( with proper permissions)
  3. User Updating( with proper permissions)
  4. User Retrieval ( with proper permissions)
  5. Login Functionality
  6. Logout Functionality

So this is it. I hope you have some idea now about the User CRUD functionality, Login and Logout.

Thanks For reading 😊

Chapi Menge.

--

--