Django Rest Framework: issue with request.data - python

I am attempting to use Django rest framework for my server implementation. I get the following error when I attempt to POST.
'WSGIRequest' object has no attribute 'data'
Here is the code for the view.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from whiteboards.models import Whiteboard, Path, Point
from whiteboards.serializers import WhiteboardSerializer
#api_view(['GET', 'POST'])
def whiteboard_list(request):
"""
List all whiteboards, or create a new whiteboard.
"""
if request.method == 'GET':
print('GET')
whiteboards = Whiteboard.objects.all()
serializer = WhiteboardSerializer(whiteboards, many=True)
return Response(serializer.data)
elif request.method == 'POST':
print('POST')
d = request.data
print('data broke')
serializer = WhiteboardSerializer(data=d)
print("created serializer")
if serializer.is_valid():
serializer.save()
print("It's valid")
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

In version 3 (latest) - request.DATA has been replaced with request.data:
user = dict(
full_name=request.data['full_name'],
password=request.data['password'],
email=request.data['email']
)
In version 2 - it was request.DATA:
user = dict(
full_name=request.DATA['full_name'],
password=request.DATA['password'],
email=request.DATA['email']
)

try request.DATA instead of request.data

Related

Django rest framework create or update in POST resquest

can anyone help please, with DRF
according to POST request, I want to create(if not exists) or update() table
belows are my codes
model.py
class User1(models.Model):
user = models.CharField(max_length=10)
full_name = models.CharField(max_length=20)
logon_data = models.DateTimeField(blank=True, null=True)
serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User1
fields = '__all__'
views.py
from .models import User1
from .serializers import UserSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view
#api_view(['GET', 'POST'])
def UserView(request):
if request.method == 'GET':
users = User1.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
elif request.method == 'POST':
users = User1.objects.all()
serializer = UserSerializer(data=request.data, many=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('users/', views.UserView),
]
when POST request, I want to check like this:
if user exists:
if user.full_name == request.fullname
update (user.logon_data)
save()
else:
update (user.full_name)
update (user.logon_data)
save()
else:
create(
user = request.user,
full_name = request.full_name,
logon_data = request.logon_date)
save()
POST request for JSON like this:
[
{
"user": "testuser1",
"full_name": "test user1",
"logon_data": "2022-10-19 09:37:26"
},
{
"user": "testuser2",
"full_name": "test user2",
"logon_data": "2022-10-20 07:02:06"
}
]
#api_view(['GET', 'POST'])
def UserView(request):
if request.method == 'GET':
users = User1.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = UserSerializer(data=request.data, many=True)
# if serializer validation fails, raises error by itself
serializer.is_valid(raise_exception=True)
for data in serializer.validated_data:
# checking if data exists else creating an object in User1 model
# user = data['user'] --> filter to check if that user exist
# defaults={'full_name': data['full_name'], 'logon_data': #data['logon_data']} --> value provided in defaults is used to update data in #model once the condition is met.
User1.objects.update_or_create(user=data['user'], defaults={'full_name': data['full_name'], 'logon_data': data['logon_data']})
return Response(serializer.data, status=201)
Try this update_or_create it will check based on request.user whether it exists in table or not
Also ensure that request.user is checked to user object if you want to check specific field then it should be request.user.user
User.objects.update_or_create(user=request.user.user, defaults={"full_name": request.full_name, "logon_date":request.logon_date})

How to add IsAuthenticated decorator only for POST method, but GET without Authentication?

How to add #permission_classes([IsAuthenticated]) to chek only for POST method IsAuthenticated?
#api_view(['GET', 'POST'])
def products_list(request):
"""
List of all Products, or create a new Products.
"""
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
P.S. Not split into two functions, i need a single view.
You can override IsAuthenticated permission like this:
class IsAuthenticated(BasePermission):
def has_permission(self, request, view):
if request.method == "GET":
return True
return bool(request.user and request.user.is_authenticated)
IsAuthenticatedOrReadOnly solved my problem.
#permission_classes([IsAuthenticatedOrReadOnly])
See: https://www.django-rest-framework.org/api-guide/permissions/#isauthenticatedorreadonly

Django REST framework - "Method \"GET\" not allowed." -

In creating Django REST framework, i'll get all the data using this code
views.py
#api_view(['GET', ])
def api_detail_educationlevel(request):
if request.method == 'GET':
educationlevel = EducationLevel.objects.all()
serializer = EducationLevelSerializer(educationlevel, many=True)
return Response(serializer.data)
urls.py
path('api/', views.api_detail_educationlevel),
but when i add in my views.py like this
#api_view(['PUT', ])
def api_update_educationlevel(request, pk):
try:
educationlevel = EducationLevel.objects.get(pk=pk)
except EducationLevel.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'PUT':
serializer = EducationLevelSerializer(educationlevel, data=request.data)
data = {}
if serializer.is_valid():
serializer.save()
data["success"] = "update successfull"
return Response(data=data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#api_view(['DELETE', ])
def api_delete_educationlevel(request, pk):
try:
educationlevel = EducationLevel.objects.get(pk=pk)
except EducationLevel.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'DELETE':
operation = educationlevel.delete()
data ={}
if operation:
data["success"] = "delete successfull"
else:
data["failure"] = "delete failed"
return Response(data=data)
#api_view(['POST', ])
def api_create_blog_view(request):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
and in my urls.py
urlpatterns = [
path('api/', views.api_detail_educationlevel),
path('api/update/', views.api_update_educationlevel),
path('api/delete/', views.api_delete_educationlevel),
path('api/create/', views.api_create_blog_view),
]
urlpatterns = format_suffix_patterns(urlpatterns)
I dont know why i am getting this message,
in my path('api/update/', views.api_update_educationlevel),
in my path('api/delete/', views.api_delete_educationlevel),
in my path('api/create/', views.api_create_blog_view),
any idea why i am getting this message? i just want functional rest framework that can update/delete/insert data using user auth account
For each of these views (views.api_detail_educationlevel, views.api_update_educationlevel, views.api_delete_educationlevel, views.api_create_blog_view), you define #api_view(['*api method*', ]).
Only the views.api_detail_educationlevel has #api_view(['GET', ]) therefore allowing a GET method. The others don't. Either add a GET method to the other views or, like the documentation you follow, create a class containing each method.

How to pass a dictionary in DestroyAPI SUccess MEssage

class ExampleDestroyView(DestroyAPIView):
serializer_class = PetSerializer
queryset = Pet.objects.all()
lookup_field = "object_id"
def perform_destroy(self, instance):
self.data = {}
self.data['status'] = True
approval()
self.data['msg'] = "It removed"
return self.data
Here is my Sample Class ..... In this I need to Delete an objet.... It's deleting
But I am unable to pass the following Dict As an OutPut
How can I pass the status and a message in a dictionary
Override the destroy(...) method
from rest_framework.generics import DestroyAPIView
from rest_framework.response import Response
from rest_framework import status
class ExampleDestroyView(DestroyAPIView):
serializer_class = PetSerializer
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
data = self.perform_destroy(instance)
return Response(data=data, status=status.HTTP_204_NO_CONTENT)
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
#api_view(['GET', 'POST'])
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Can't get a GET response in DJango Rest

I'm trying to learn DJango Rest so I made a litte test to see if I could obtain some things from the database, but I'm getting some problems.
Here's my models.py:
from django.db import models
# Create your models here.
class Stock(models.Model):
ticker = models.CharField(max_length=10)
open = models.FloatField()
close = models.FloatField()
volume = models.IntegerField()
def __str__(self):
return self.ticker
Here's my serializers.py:
from rest_framework import serializers
from .models import Stock
class StockSerializer(serializers.ModelSerializer):
ticker = serializers.CharField()
open = serializers.FloatField()
close = serializers.FloatField()
volume = serializers.IntegerField()
def create(self, validated_data):
return Stock.objects.check(**validated_data)
def update(self, instance, validated_data):
instance.ticker = validated_data.get('ticker', instance.ticket)
instance.open = validated_data.get('open', instance.open)
instance.close = validated_data.get('close', instance.close)
instance.volume = validated_data.get('volume', instance.volume)
instance.save()
return instance
class Meta:
model = Stock
fields = '__all__'
Here's my views.py:
from django.http import Http404
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Stock
from .serializers import StockSerializer
# List all stocks or create a new one
# stocks/
#api_view(['GET', 'POST'])
def stock_list(request, format=None):
if request.method == 'GET':
stocks = Stock.objects.all()
serializer = StockSerializer(stocks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = StockSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#api_view(['GET', 'POST', 'DELETE'])
def stock_detail(request, pk, format=None):
try:
stock = Stock.objects.get(pk=pk)
except Stock.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = StockSerializer(stock)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = StockSerializer(stock, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
stock.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
And finally, here's my url.py:
from django.conf.urls import url
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from companies import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^stocks/', views.stock_list),
url(r'^stocks/(?P<pk>[0-9]+)$', views.stock_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)
I've been following this tutorial, but when it comes to the moment of making some requests (for this example I use this one: http http://127.0.0.1:8000/stocks/
I get this error message:
TypeError at /stocks/ stock_list() missing 1 required positional
argument: 'request'
I think that the problem is with the urls, but I'm not sure how to fix it.
Any ideas and some examples?
UPDATE: The problem was with the methods in view (they had an attibute self)
The general Get method works, but when I try to use POST
POST ERROR:
When I try this request: http --form POST http://127.0.0.1:8000/stocks/ ticker='SAM'
I get this error:
AttributeError at /stocks/ Got AttributeError when attempting to get a
value for field ticker on serializer StockSerializer. The
serializer field might be named incorrectly and not match any
attribute or key on the list instance. Original exception text was:
'list' object has no attribute 'ticker'.
You need to remove self.
Remember you are using functions not clases.
#api_view(['GET', 'POST'])
def stock_list(request, format=None):
if request.method == 'GET':
stocks = Stock.objects.all()
serializer = StockSerializer(stocks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = StockSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Try views.stock_list.as_view() in urls.py

Categories