Reputation: 372
I am new to django rest framework. I was trying to build a API where I want to edit the POST method so that I could execute some actions and change some data from the POST body. I tried to follow some documentations and Guide from django rest framework website but didnt followed any. Please help me.
Here I need to set some values for some fields that are going to be saved in the database. views.py
from .models import LoginActivity
from .serializers import LoginActivitySerializers
class LoginActivity(viewsets.ModelViewSet):
queryset = LoginActivity.objects.all()
serializer_class = LoginActivitySerializers
urls.py
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'LoginActivity', views.LoginActivity, basename='LoginActivity')
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
appname='api'
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
serializers.py
from rest_framework import serializers
from .models import LoginActivity
class LoginActivitySerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = LoginActivity
fields = ('id', 'user_id', 'datetimelog', 'device_os', 'device_token', 'device_model')
Please Help me.
Upvotes: 0
Views: 139
Reputation: 1714
you can override rest framework create
method which come from viewsets.ModelViewSet
and update request data or perform some other actions.
from .models import LoginActivity
from .serializers import LoginActivitySerializers
class LoginActivity(viewsets.ModelViewSet):
queryset = LoginActivity.objects.all()
serializer_class = LoginActivitySerializers
def create(self, request, *args, **kwargs):
# here you have your post data in request.data
data = request.data
# you can do some action here just before create action
# after that you can call super method or return your response
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(status=status.HTTP_201_CREATED)
Upvotes: 1