django - TemplateDoesNotExist error - python

I am working through this Getting started with Django Rest Framework by Building a Simple Product Inventory Manager tutorial. At the end the tutorial, it says that I "should now be able to run your server and start playing with diffrent API endpoints". However, when I run the server, all I'm getting is a TemplateDoesNotExist error. At no point in the tutorial does it mention creating templates (and this is eventually going to connect to an Angular 2 frontend, as shown in this tutorial), so I'm confused at to whether this is an error in my code, or if the tutorial left a step out. I do not get any console errors when I run my code.
serializers.py
from .models import Product, Family, Location, Transaction
from rest_framework import serializers
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = ('reference', 'title', 'description')
class FamilySerializer(serializers.ModelSerializer):
class Meta:
model = Family
fields = ('reference', 'title', 'description', 'unit', 'minQuantity')
class ProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Product
fields = ('sku', 'barcode', 'title', 'description', 'location', 'family')
depth = 1
class TransactionSerializer(serializers.ModelSerializer):
product = ProductSerializer()
class Meta:
model = Transaction
fields = ('sku', 'barcode', 'product')
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import status, generics, mixins
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Product, Location, Family, Transaction
from .serializers import *
# Create your views here.
#api_view(['GET', 'POST'])
def product_list(request):
"""
List all products, or create a new product.
"""
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products,context={'request': request} ,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)
#api_view(['GET', 'PUT', 'DELETE'])
def product_detail(request, pk):
"""
Retrieve, update or delete a product instance.
"""
try:
product = Product.objects.get(pk=pk)
except Product.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = ProductSerializer(product,context={'request': request})
return Response(serializer.data)
elif request.method == 'PUT':
serializer = ProductSerializer(product, data=request.data,context={'request': request})
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
product.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class family_list(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
queryset = Family.objects.all()
serializer_class = FamilySerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class family_detail(generics.RetrieveUpdateDestroyAPIView):
queryset = Family.objects.all()
serializer_class = FamilySerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class location_list(generics.ListCreateAPIView):
queryset = Location.objects.all()
serializer_class = LocationSerializer
class location_detail(generics.RetrieveUpdateDestroyAPIView):
queryset = Location.objects.all()
serializer_class = LocationSerializer
class transaction_list(generics.ListCreateAPIView):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
class transaction_detail(generics.RetrieveUpdateDestroyAPIView):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
IF you need to see more of my code, please comment and I'll post it, but everything should be identical to the code given in the tutorial.

May be you could forget to add "rest_framework" in installed apps(settings.py).
INSTALLED_APPS = (
...
'rest_framework',
)
http://www.django-rest-framework.org/#installation

Related

Django filters with APIVIew return the complete queryset

I'm trying to use django filter with APIVIew like I saw in this post and I'm geting an unexpected behavior:
If the word passed on filter doesn't exists, it return nothing - OK
If the word passed on filter exists, it return the complete queryset.
I tried to use filters with ModelViewSet before and it works, but I have no success with APIView. I'm using the following code:
views:
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from core.models import Profile
from core.serializers import ProfileSerializer
from django_filters.rest_framework import DjangoFilterBackend
class ProfileFilter(DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
filter_class = self.get_filter_class(view, queryset)
if filter_class:
return filter_class(request.query_params, queryset=queryset, request=request).qs
return queryset
class ListProfileView(APIView):
serializer_class = ProfileSerializer
filter_fields = ('nome', 'link')
queryset = Profile.objects.all()
def get(self, request, format=None):
queryset = Profile.objects.all()
ff = ProfileFilter()
filtered_queryset = ff.filter_queryset(request, queryset, self)
if filtered_queryset.exists():
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response([], status=status.HTTP_200_OK)
def post(self, request, format=None):
serializer = self.serializer_class(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)
model:
from django.db import models
class Profile(models.Model):
nome = models.CharField(max_length=200, null=False, blank=False)
link = models.CharField(max_length=200, null=False, blank=False)
serializers:
from rest_framework.serializers import ModelSerializer
from core.models import Profile
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
fields = '__all__'

Filtering by Foreign Key in ViewSet, django-rest-framework

I want my api to return certain objects from a database based on the foreign key retrieved from the url path. If my url looks like api/get-club-players/1 I want every player object with matching club id (in this case club.id == 1). I'm pasting my code down below:
models.py
class Club(models.Model):
name = models.CharField(max_length=25)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Player(models.Model):
name = models.CharField(max_length=30)
club = models.ForeignKey(Club, on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.name
serialziers.py
class ClubSerializer(serializers.ModelSerializer):
class Meta:
model = Club
fields = 'id', 'owner', 'name'
class PlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player
fields = 'id', 'name', 'offense', 'defence', 'club', 'position'
views.py, This is the part where I get the most trouble with:
class ClubViewSet(viewsets.ModelViewSet):
queryset = Club.objects.all()
serializer_class = ClubSerializer
class PlayerViewSet(viewsets.ModelViewSet):
queryset = Player.objects.all()
serializer_class = PlayerSerializer
class GetClubPlayersViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Player.objects.all()
serializer = PlayerSerializer(queryset, many=True)
def retrieve(self,request, clubId):
players = Player.objects.filter(club=clubId, many=True)
if not players:
return JsonResponse({'error': "No query found!"})
else:
serializer = PlayerSerializer(players)
return Response(serializer.data)
urls.py
from rest_framework import routers
from django.urls import path, include
from .views import (GameViewSet, PlayerViewSet, ClubViewSet,
GetClubPlayersViewSet, create_club, set_roster)
router = routers.DefaultRouter()
router.register(r'clubs', ClubViewSet, basename="clubs")
router.register(r'players', PlayerViewSet, basename="players")
router.register(r'get-club-players', GetClubPlayersViewSet, basename="club-players")
urlpatterns = [
path('', include(router.urls)),
]
EDIT:
Now views.py looks like that:
class GetClubPlayersViewSet(viewsets.ViewSet):
queryset = Player.objects.all()
def list(self, request):
serializer = PlayerSerializer(self.queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, *args, **kwargs):
clubId = kwargs['get-club-players']
players = Player.objects.filter(club=clubId, many=True)
if not players:
return JsonResponse({'error': "No query found!"})
else:
serializer = PlayerSerializer(players)
return Response(serializer.data)
http://127.0.0.1:8000/api/get-club-players/ returns all of the player objects, but when I ad a clubId into url I get this error:
EDIT 2:
class GetClubPlayersViewSet(viewsets.ViewSet):
queryset = Player.objects.all()
def retrieve(self, request, *args, **kwargs):
queryParams = self.request.GET.get('abc')
if queryParams is None:
queryset = Player.objects.none()
else:
queryset = Player.objects.filter(club = queryParams)
serializer = PlayerSerializer(queryset)
return Response(serializer.data)
def list(self, request):
serializer = PlayerSerializer(self.queryset, many=True)
return Response(serializer.data)
You can get url parameters using kwargs attribute. You will need to modify the signature of your retrieve method for it.
def retrieve(self, request, *args, **kwargs):
clubId = kwargs['get-club-players']
players = Player.objects.filter(club=clubId, many=True)
....
EDIT
For the queryset error, it is due to DRF requiring either the queryset class attribute or implementation of get_queryset() function. In your case, you can get around it like this:
class GetClubPlayersViewSet(viewsets.ViewSet):
queryset = Player.objects.all()
def list(self, request):
serializer = PlayerSerializer(self.queryset, many=True)
So you can define your queryset like -
def get_queryset(self):
queryParams == self.request.GET.get('abc') # get queryparameter from url
if queryParams is None:
#queryset = anyModel.objects.all()
queryset = anyModel.objects.none()
else:
queryset = anyModel.objects.filter(anyProperty = queryParams)
return queryset
and your url will be like -
api/get-club-players/?abc=1
this abc can be id or any other property from the model.
Use this get_queryset logic in your retrieve method.
rest_framework.viewsets.ViewSet has an attribute named lookup_field which you can override. By default the value of lookup_field is id.
When adding the viewset in router, the lookup_field is added as the argument name in the url (e.g. /api/get-club-players/:id/).
You can either override the lookup_field of GetClubPlayersViewSet or access the correct kwargs key by changing
clubId = kwargs['get-club-players'] to clubId = kwargs['id']
Or a bit of both:
class GetClubPlayersViewSet(viewsets.ViewSet):
lookup_field = "clubId"
queryset = Player.objects.all()
# ....
def retrieve(self, request, *args, **kwargs):
clubId = kwargs[self.lookup_field]
players = Player.objects.filter(club=clubId, many=True)
if not players:
return JsonResponse({'error': "No query found!"})
else:
serializer = PlayerSerializer(players)
return Response(serializer.data)

How to use has_object_permission with APIView in Django Rest Framework?

Hi everyone I want to use a custom permission with APIView in my class UserDetail but I noticed that this permission is not executing, my permission is called "IsOwner", because I want to allow users to modify his own information based on the user id. Every time that I make a request I got an error:
{
"detail": "Not found."
}
views.py
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status, permissions, generics, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import MyTokenObtainPairSerializer, UserSerializer, GroupSerializer
from .models import User
from authentication.permisssions import CustomObjectPermissions, IsOwner
from django.contrib.auth.models import Group
from django.http import Http404
class ObtainTokenPairView(TokenObtainPairView):
permission_classes = [permissions.AllowAny,]
serializer_class = MyTokenObtainPairSerializer
class UserList(APIView):
"""
List all snippets, or create a new snippet.
"""
permission_classes = [CustomObjectPermissions]
serializer_class = UserSerializer
def get_queryset(self):
users = User.objects.all().order_by('-date_joined')
return users
def get(self, request, format=None):
serializer_context = {
'request': request,
}
serializer = UserSerializer(self.get_queryset(), context=serializer_context, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer_context = {
'request': request,
}
serializer = UserSerializer(data=request.data, context=serializer_context)
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)
class UserDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
permission_classes = [CustomObjectPermissions|IsOwner]
serializer_class = UserSerializer
def get_queryset(self):
pk = self.kwargs["pk"]
return User.objects.filter(id = pk)
def get_object(self, pk):
try:
print(pk)
user = User.objects.get(pk=pk)
self.check_object_permissions(self.request, user)
return user
except User.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
user = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = UserSerializer(user, context=serializer_context)
return Response(serializer.data)
def put(self, request, pk, format=None):
user = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = UserSerializer(user,context=serializer_context, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class GroupList(APIView):
"""
List all snippets, or create a new snippet.
"""
permission_classes = [CustomObjectPermissions]
queryset = Group.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
def get(self, request, format=None):
groups = Group.objects.all()
serializer_context = {
'request': request,
}
serializer = GroupSerializer(groups, context=serializer_context, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer_context = {
'request': request,
}
serializer = GroupSerializer(data=request.data, context=serializer_context)
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)
class GroupDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
permission_classes = [CustomObjectPermissions]
queryset = Group.objects.all().order_by('-date_joined')
serializer_class = GroupSerializer
def get_object(self, pk):
try:
return Group.objects.get(pk=pk)
except Group.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
group = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = GroupSerializer(group, context=serializer_context)
return Response(serializer.data)
def put(self, request, pk, format=None):
group = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = GroupSerializer(group,context=serializer_context, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
group = self.get_object(pk)
group.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
permissions.py
from rest_framework.permissions import DjangoObjectPermissions, BasePermission
class CustomObjectPermissions(DjangoObjectPermissions):
"""
Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
"""
perms_map = {
'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
'HEAD': ['%(app_label)s.view_%(model_name)s'],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}
class IsOwner(BasePermission):
message = 'You must be the owner of this object'
def has_object_permission(self, request, view, obj):
return obj.id == request.user.id
views.py (self.check_object_permissions(self.request, user) this line is not working)
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status, permissions, generics, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import MyTokenObtainPairSerializer, UserSerializer, GroupSerializer
from .models import User
from authentication.permisssions import CustomObjectPermissions, IsOwner
from django.contrib.auth.models import Group
from django.http import Http404
class ObtainTokenPairView(TokenObtainPairView):
permission_classes = [permissions.AllowAny,]
serializer_class = MyTokenObtainPairSerializer
class UserList(APIView):
"""
List all snippets, or create a new snippet.
"""
permission_classes = [CustomObjectPermissions]
serializer_class = UserSerializer
def get_queryset(self):
users = User.objects.all().order_by('-date_joined')
return users
def get(self, request, format=None):
serializer_context = {
'request': request,
}
serializer = UserSerializer(self.get_queryset(), context=serializer_context, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer_context = {
'request': request,
}
serializer = UserSerializer(data=request.data, context=serializer_context)
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)
class UserDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
permission_classes = [CustomObjectPermissions|IsOwner]
serializer_class = UserSerializer
def get_queryset(self):
pk = self.kwargs["pk"]
return User.objects.filter(id = pk)
def get_object(self, pk):
try:
print(pk)
user = User.objects.get(pk=pk)
self.check_object_permissions(self.request, user)
return user
except User.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
user = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = UserSerializer(user, context=serializer_context)
return Response(serializer.data)
def put(self, request, pk, format=None):
user = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = UserSerializer(user,context=serializer_context, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class GroupList(APIView):
"""
List all snippets, or create a new snippet.
"""
permission_classes = [CustomObjectPermissions]
queryset = Group.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
def get(self, request, format=None):
groups = Group.objects.all()
serializer_context = {
'request': request,
}
serializer = GroupSerializer(groups, context=serializer_context, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer_context = {
'request': request,
}
serializer = GroupSerializer(data=request.data, context=serializer_context)
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)
class GroupDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
permission_classes = [CustomObjectPermissions]
queryset = Group.objects.all().order_by('-date_joined')
serializer_class = GroupSerializer
def get_object(self, pk):
try:
return Group.objects.get(pk=pk)
except Group.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
group = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = GroupSerializer(group, context=serializer_context)
return Response(serializer.data)
def put(self, request, pk, format=None):
group = self.get_object(pk)
serializer_context = {
'request': request,
}
serializer = GroupSerializer(group,context=serializer_context, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
group = self.get_object(pk)
group.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
If you need the operator Or ,you can import rest_condition:
pip install rest_condition
And in your view import Or from rest_condition and do the following on the permission_classes:
permission_classes = [Or(CustomObjectPermissions,IsOwner)]
But I don't think the error is caused because Or is missing,you can tackle this problem from another prespective, you can have the get request returning only that user's information so he can modify:
def get_queryset(self):
serializer = self.get_serializer()
owner = serializer.context['request'].user
return User.objects.filter(id=owner.id)

How to get user by Token in django Rest

Using:
class PostSerializer(serializers.ModelSerializer):
author = ExtUserSerializer(required=False, allow_null=True)
class Meta:
model = Post
field = ('title','description','rating','author')
def create(self, validated_data):
return Post.objects.create(**validated_data)
and
#api_view(['GET'])
def post_list(request, format=None):
if request.method == 'GET':
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
How to modify Serializer and view to fill field author automatically

Django AttributeError: Module object has no attribute 'PersonsList'

I'm working on a web app using the Django rest framework tutorial. I'm trying to load JSON data on my project site using the dev server. However, every time I go to the address, it returns a HTTP 500 error with an AttributeError that says: 'module' object has no attribute 'PersonsList'.
I followed the entire tutorial, edited the urls and views py files a bunch of times, yet I keep getting the same error. Any suggestions of how to fix this?
Here's my code.
urls.py
from django.conf.urls import patterns, url
from pros import views
urlpatterns = patterns ('',
url(r'^pros/$', views.PersonsList.as_view(), name='PersonsList')
)
models.py
from django.db import models
# Create a "Persons" class to add new input field datatypes
class Persons(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Meta:
ordering = ('created',)
serializers.py
from django.forms import widgets
from rest_framework import serializers
from persons.models import Persons, LANGUAGE_CHOICES, STYLE_CHOICES
class PersonsSerializer(serializers.Serializer):
pk = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
def create(self, validated_data):
"""
Create and return a new 'Persons' instance, given the validated data.
"""
return Persons.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing 'Persons' instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos)
instance.language = validated_data.get('language', instance.language)
instance.style = validated_data.get('style', instance.style)
instance.save()
return instance
views.py
from pros.models import Persons
from pros.serializers import PersonsSerializer
from django.http import Http404
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
class PersonsList (mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Persons.objects.all()
serializer_class = PersonsSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class PersonsDetail (mixins.RetrieveModleMixin,
mixins. UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Persons.objects.all()
serializer_class = PersonsSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
#api_view(['GET', 'POST'])
def persons_list(request):
def persons_list(request, format=None):
"""List all persons, or create a new person
"""
if request.method == 'GET':
persons = Persons.objects.all()
serializer = PersonsSerializer(persons, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = PersonsSerializer(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)
directorystructure.txt

Categories