Automatically Add Logged In User Under 'created_by' and 'updated_by' to Model in Django Rest Framework

forhadakhan

Forhad Khan

Posted on November 5, 2022

Automatically Add Logged In User Under 'created_by' and 'updated_by' to Model in Django Rest Framework

In some application, we need to track which user added or updated the data in the system. So here we will see how to do this job in the background without any user input.

Required setup:
I hope you already have Django and the Django Rest Framework installed. If not, please install these first.

run -



pip install Django 
pip install djangorestframework 


Enter fullscreen mode Exit fullscreen mode

Settings:

In your settings.py add 'rest_framework' and your internal apps e.g. 'api'.



INSTALLED_APPS = [
    #......

    # third-party packages
    'rest_framework',

    # internal apps
    'api',
]


Enter fullscreen mode Exit fullscreen mode

Write models:

Define your applications model in models.py



from django.db import models
from django.conf import settings

class Student(models.Model):
    name = models.CharField(max_length=180)
    programme = models.CharField(max_length=250)
    batch = models.SmallIntegerField()
    roll = models.SmallIntegerField()
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='created_by', blank=True, null=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='updated_by', blank=True, null=True)



Enter fullscreen mode Exit fullscreen mode

Write Serializers:

Inside your application, add a file called serializers.py and define a serializer class for your model as follows:



from rest_framework import serializers
from .models import Student

class StudentModelSerializer(serializers.ModelSerializer):
    created_by = serializers.StringRelatedField(default=serializers.CurrentUserDefault(), read_only=True)
    updated_by = serializers.StringRelatedField(default=serializers.CurrentUserDefault(), read_only=True)
    class Meta:
        model = Student
        fields = ['id', 'name', 'programme', 'batch', 'roll', 'created_by', 'updated_by']



Enter fullscreen mode Exit fullscreen mode

Admin:

You can register your model in admin.py in case you want to add data from the Django admin panel:



from django.contrib import admin
from .models import Student

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'programme', 'batch', 'roll']



Enter fullscreen mode Exit fullscreen mode

View:

Now, write your view.py, and please make sure to add authentication as we have to work with users:



from .models import Student
from .serializers import StudentModelSerializer
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.authentication import SessionAuthentication


class StudentModelViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticatedOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user)



Enter fullscreen mode Exit fullscreen mode

URLs:

If you didn't define URLs for your views, then define it in urls.py.



from django.contrib import admin
from django.urls import path, include 
from rest_framework.routers import DefaultRouter
from api.views import *  

# Create Router Object
router = DefaultRouter()

# Register View Class with Router
router.register('student', StudentModelViewSet, basename='student_')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
    path('auth/', include('rest_framework.urls', namespace='rest_framework'))
]



Enter fullscreen mode Exit fullscreen mode

Make Migrations:

Migration is necessary after changes in models.

run -



python manage.py makemigrations 
python manage.py migrate


Enter fullscreen mode Exit fullscreen mode

Users:

So this is what we are working for; to add a logged-in user automatically, you must have users registered in your system. So if you don't have any registered users, then add some. If you are using the Django default system, then you can manage users from the Django admin panel.

It's time to see the outcomes.

Go to the URL in browser:

Go to the URL in browser

Login to a user:

Login to a user

Add a new data:

Add a new data

Look at the data, automatically added logged user info to created_by field:

Look at the data, automatically added logged user info to created_by field

Now update a data:

Now update a data

Look at the data, automatically added logged user info to updated_by field:

Look at the data, automatically added logged user info to updated_by field

💖 💪 🙅 🚩
forhadakhan
Forhad Khan

Posted on November 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related