Logo

dev-resources.site

for different kinds of informations.

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

Published at
11/5/2022
Categories
django
drf
djangorestframework
python
Author
forhadakhan
Author
11 person written this
forhadakhan
open
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

drf Article's
30 articles in total
Favicon
Djoser+SimpleJWT
Favicon
AssertionError: 403
Favicon
extra_kwargs arguments
Favicon
To Django or to DjangoREST?
Favicon
Django API | queryset & object, filter() & get()
Favicon
I just tried to compare values between model and serializer
Favicon
Customize Schema with @extend_schema_view
Favicon
Seperate serializers
Favicon
Leveraging Headers for Dynamic Localization in Django
Favicon
Django REST Framework warning: `UnorderedObjectListWarning`
Favicon
DRF create @property decorator in view and use property in serializer
Favicon
why Serializers used for? easy to understand
Favicon
Async API Calls Unleashed: Exploring Django 4 and Django Rest Framework
Favicon
# Comprehensive Security for Class-Based Views in Django Rest Framework
Favicon
HATEOAS Principle - Generating Full Paths for Objects in Django Rest Framework.
Favicon
Instance version control in DRF with Django Reversion
Favicon
Django News #171 - DjangoCon US 2023 Preview
Favicon
How to create thumbnails programmatically in Django
Favicon
Automatically Add Logged In User Under 'created_by' and 'updated_by' to Model in Django Rest Framework
Favicon
how to fix raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
Favicon
CSRF verification failed. Request aborted. in django rest framework
Favicon
CSRF verification failed. Request aborted. in django rest framework
Favicon
How to fix "Must supply api_key"
Favicon
Updating A Many-To-Many Relationship In Django
Favicon
Excluding Fields in Django Rest Framework Serializers
Favicon
JWT Authentication with Django REST Framework - What? Why? How?
Favicon
How to implement Auto Expiring Token in Django Rest Framework
Favicon
Building web applications with Django, Django REST Framework and Nuxt
Favicon
How to use Postman to authenticate to Django Rest Framework
Favicon
Setting Up Django Rest Framework

Featured ones: