Rename field in Serializer.data - django-rest-framework

I am currently implementing an API client for which I want to validate the request sent using serializers.
To do so, I create my serializer like this:
class TransactionRequestSerializer(serializers.Serializer):
counterparty = serializers.UUIDField(required=False)
from_datetime = serializers.DateTimeField(required=False, source='from')
to_datetime = serializers.DateTimeField(required=False, source='to')
transaction_type = serializers.CharField(required=False, source='type')
Issue is that source doesn't fit my usage, because when I do serializer.data, I get:
{'from_datetime': '2020-07-07T16:08:00.313236+02:00'}
Instead of
{'from': '2020-07-07T16:08:00.313236+02:00'}
Those data are then passed as params for my request, like requests.get('', params=params)
Of course, I cannot name the field "from" as it is reserved. Any idea about how can I get "from" in my serializer.data?

I tink this has already been answered.
Please take a look at this question: How to change field name in Django REST Framework
I think the same solution will work for you.

I think it's not possible, so I switched to Serializer.validated_data instead so I can use source.

this example as same the question :
model:
from django.db import models
class ReceiveCallbackUrl(models.Model):
From = models.CharField(max_length=14)
to = models.CharField(max_length=14)
message = models.CharField(max_length=255)
messageid = models.IntegerField()
serializer:
from rest_framework.serializers import ModelSerializer,SerializerMethodField
from .models import ReceiveCallbackUrl
class ReceiveCallbackUrlModelSerializer(ModelSerializer):
From = SerializerMethodField('from')
class Meta:
model = ReceiveCallbackUrl
fields = ['From', 'to', 'message', 'messageid']
view:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializer import ReceiveCallbackUrlModelSerializer
class ReceiveCallbackUrlAPIView(APIView):
def post(self, request):
serializer = ReceiveCallbackUrlModelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(request.POST, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

Related

PUT request doesn't update - Django Rest Framework

I'm trying to build a todos app using django-rest-framework and when I send PUT request to change the content of the task, the content is still the same. It seems that the serializer.save() is not working as I expected.
Here are the code:
views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import Note
from .serializers import NoteSerializer
#api_view(['PUT'])
def updateNote(request, pk):
note = Note.objects.get(id=pk)
serializer = NoteSerializer(instance=note, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
models.py
from django.db import models
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
serializers.py
from rest_framework.serializers import ModelSerializer
from .models import Note
class NoteSerializer(ModelSerializer):
class Meta:
model = Note
fields = '__all__'
I'm learning django so this is kinda new to me. I had searched for this problem but I'm kinda new to django so I don't understand these answers much. Any help would be appreciated.
#api_view(['PUT'])
def updateNote(request, self, pk):
note = get_object_or_404(Note.objects.all(), pk=pk)
serializer = NoteSerializer(instance=note, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)

Assertation Error, You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation

I'm learning drf. I created api using it for minimarket app. After creating some data, i tried to get all of them and i got AssertationError like "You passed a Serializer instance as data, but probably meant to pass serialized .data or .error. representation.
" :( Who knows, what can i do?
views.py
#api_view(['GET'])
def view_items(request):
# checking for the parameters from the URL
items = Item.objects.all()
# if there is something in items else raise error
if items:
return Response(ItemSerializer(items))
else:
return Response(status=status.HTTP_404_NOT_FOUND)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ApiOverview, name='home'),
path('create/', views.add_items, name='add-items'),
path('all/', views.view_items, name='view_items'),
]
serializers.py
from pyexpat import model
from django.db.models import fields
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('category', 'subcategory', 'name', 'amount')
As the error says, you can not return a serializer in the response:
return Response(ItemSerializer(items))
You can return the data of the serializer, so:
#api_view(['GET'])
def view_items(request):
# checking for the parameters from the URL
items = Item.objects.all()
serializer = ItemSerializer(items, many=True)
# if there is something in items else raise error
if items:
return Response(serializer.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)

Record exists or not in DB? Django Api generic Views

I want to write a class based API view to check if the record exists in DB or not then return True else False by using rest_framework. How could I create CBV to check it? Please help me with this context.
here is my serializer class
class EmployeeSerializer(ModelSerializer):
class Meta:
model = Employee
fields = '__all__'
here is my url
path('employee/<name>/<code>/',views.EmployeeExist.as_view(),name = 'employee_exits')
Here is how you can create simple view:
from rest_framework import status, response
from rest_framework import generics
class EmployeeExistView(generics.GenericAPIView):
serializer_class = None
def get(self, request, *args, **kwargs):
employee = Employee.objects.filter(id=kwargs.get('id'))
if employee.exists():
return response.Response(status=status.HTTP_200_OK)
return response.Response(status=status.HTTP_404_NOT_FOUND)

How to create view from External http request json and Internal Database using Django Rest Framework

I need to combine external json using request and Internal Database, But the condition is when someone call API we need to get empidlong from Model for call external API from specific URL, Then external API will return JSON and i need to merge this JSON with my json that create by Django REST API Framework
Here is my code
models.py :
from django.db import models
import requests
from django.core.files import File
from urllib import request
import os
# Create your models here.
class getData(models.Model):
company = models.CharField(max_length=150)
description = models.CharField(max_length=150)
period = models.CharField(max_length=150)
plate_no = models.CharField(max_length=150, primary_key=True)
project_code = models.CharField(max_length=150)
costcenter = models.CharField(max_length=150)
empidlong = models.CharField(max_length=150)
class Meta:
db_table = 'car_information'
serializers.py
from rest_framework import serializers
from .models import getData
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = getData
fields = "__all__"
views.py
from django.shortcuts import render
from rest_framework import viewsets, filters
from .models import getData
from .serializers import CarSerializer
import requests
class CarViewSet(viewsets.ModelViewSet):
queryset = getData.objects.all()
serializer_class = CarSerializer
filter_backends = (filters.SearchFilter,)
#search_fields = ('plate_no')
__basic_fields = ('plate_no',)
search_fields = __basic_fields
serializer = CarSerializer(queryset, many=True)
data = serializer.data
for a in data:
empid= a['empidlong']
r = requests.get('http://192.168.10.32/Employees/'+empid)
def get_queryset(self):
queryset = getData.objects.all()
emp = self.request.query_params.get('emp', None)
if emp is not None:
queryset = queryset.filter(empidlong=emp)
return queryset
I have no idea how to do it. I stuck this for week.
Thank in advance.
Where are you expecting the json from? if from a user, you can access the json from the request. Then you can use it in your orm query. You CarViewSet seem to be doing way more than it should be. What is your goal exactly?

restframework-jwt how can I handle payload?

I used Django restframework to implement api server.
Also I used djangorestframework-jwt for token authentication.
[urls.py]
from django.contrib import admin
from django.urls import path, include
from rest_framework_jwt.views import refresh_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('rest_auth.urls')),
path('registration/', include('rest_auth.registration.urls')),
path('refresh-token/', refresh_jwt_token),
]
Everything works fine. But I want to know that How can I extract payload from token?
For example, There is article table.
[/article/serializers.py]
from rest_framework import serializers
from . import models
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = models.Article
fields = '__all__'
[models.py]
from django.db import models
class Article(models.Model):
subject = models.CharField(max_length=20)
content = models.CharField(max_length=100)
[views.py]
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
class Article(APIView):
def get(self, request, format=None):
all_article = models.Article.objects.all()
serializer = serializers.ArticleSerializer(all_article, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
In this case, I want to return correct response only payload['userid'] == article's userid.
How can I extract username from jwt token?
Previous, I just use jwt not djangorestframework-jwt, So just decode request data and use it.
But now I use djangorestframework-jwt, I confused How can I do it.
Is there any solution about this?
Thanks.
I solved this issue after checking the library's documentation here
https://jpadilla.github.io/django-rest-framework-jwt/
I needed to Override all the functions to return custom response as required in my application.
Also any additional settings we need to specify in JWT_AUTH in settings.py of my application.
i.e.
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER':
'myapp.utils.jwt_response_payload_handler',
}
And needed to define jwt_response_payload_handler function in a util folder in my app to override the default function.

Resources