Django AttributeError: Module object has no attribute 'PersonsList' - python

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

Related

How to send images to DRF with json request?

I am working on an e-commerce project, and I want to add products from the front end. The files in my product app in Django is as follows
models.py:
from django.db import models
from django.forms import CharField
from PIL import Image
from io import BytesIO
from django.core.files import File
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
def get_absolute_url(self):
return f'/{self.slug}/'
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
slug = models.SlugField()
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=6, max_digits=6)
image = models.ImageField(upload_to='uploads/', blank=True, null=True)
thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
def create_thumbnail(self, image, size = (300,200)):
img = Image.open(image)
img.convert('RGB')
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'JPEG')
thumbnail = File(thumb_io, name=image.name)
return thumbnail
def get_image(self):
if self.image:
return f'http://localhost:8000' + self.image.url
else:
return ''
def get_thumbnail(self):
if self.thumbnail:
return f'http://localhost:8000' + self.thumbnail.url
else:
if self.image:
self.thumbnail = self.create_thumbnail(self.image)
self.save()
return f'http://localhost:8000' + self.thumbnail.url
else:
return ''
def get_absolute_url(self):
return f'/{self.slug}/'
views.py:
from sys import excepthook
from unicodedata import category
from django.http import Http404
from django.shortcuts import render
from .serializers import ProductSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Product
from rest_framework import status
# Create your views here.
class LastestProduct(APIView):
def get(self, request, format=None):
products = Product.objects.all()[0:4]
serializer = ProductSerializer(products, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class Productclass LastestProduct(APIView):
def get(self, request, format=None):
products = Product.objects.all()[0:4]
serializer = ProductSerializer(products, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class ProductDetail(APIView):
def get_object(self, category_slug, product_slug):
try:
return Product.objects.filter(category__slug = category_slug).get(slug=product_slug)
except Product.DoesNotExits:
raise Http404
def get(self, request, category_slug, product_slug, format=None):
product = self.get_object(category_slug, product_slug)
serializer = ProductSerializer(product)
return Response(serializer.data, status=status.HTTP_200_OK)(APIView):
def get_object(self, category_slug, product_slug):
try:
return Product.objects.filter(category__slug = category_slug).get(slug=product_slug)
except Product.DoesNotExits:
raise Http404
def get(self, request, category_slug, product_slug, format=None):
product = self.get_object(category_slug, product_slug)
serializer = ProductSerializer(product)
return Response(serializer.data, status=status.HTTP_200_OK)
serializers.py:
from dataclasses import fields
from pyexpat import model
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = [
'id',
'name',
'category',
'get_absolute_url',
'description',
'price',
'get_image',
'get_thumbnail',
]
It works fine when it comes to fetching data (products I created in the Django admin) but how to send a JSON request that also contains the images as well as the text data like name, description etc. Currently, I can create a product by sending a POST request but the cannot send an image to the endpoint
Actually, you don't. If you want to send a file, you'd better send it as a multipart/formdata not json.
In DRF, this requires you change the default parser of your view.
See: https://www.django-rest-framework.org/api-guide/parsers/#multipartparser
But, if you really need to use a json format, I guess you could transform your file into a str representation (in the front - check base64 encoding) then send it in a json and finally transform the str representation into a file in the back. However, I would not advise you to do this as it makes the process more cumbersome

I want to restrict a particular user from creating a saved class object if the current user id is different from the id in the live class object

My models.py
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.utils import timezone
# Create your models here.
class LiveClass(models.Model):
standard = models.IntegerField()
no_of_students_registered = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'Class'
def __str__(self):
return str(self.standard) + ' class'
class User_details(models.Model):
name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30)
standard = models.IntegerField(default=0)
email = models.EmailField()
mobile_number = models.IntegerField()
class Meta:
verbose_name_plural = 'User_details'
def __str__(self):
return str(self.name)
class Mentor(models.Model):
name = models.CharField(max_length=30)
details = models.TextField()
ratings = models.FloatField(default=2.5)
class Meta:
verbose_name_plural = 'Mentors'
def __str__(self):
return self.name
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_name = models.CharField(max_length=30)
chapter_details = models.TextField()
mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
class_time = models.DateTimeField()
end_time = models.DateTimeField(default=timezone.now())
isDoubtClass = models.BooleanField(default=False)
doubtsAddressed = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
def __str__(self):
return self.chapter_name
class SavedClass(models.Model):
class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
is_registered = models.BooleanField(default=False)
is_attended = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'SavedClasses'
def __str__(self):
return 'SavedClass : ' + str(self.class_details)
my views.py
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import generics
from django.contrib.auth.mixins import LoginRequiredMixin
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework.response import Response
from django.contrib.auth import authenticate
from . import serializers
from . import models
# Create your views here.
class ListLiveClass(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class LiveClassView(mixins.ListModelMixin,
mixins.CreateModelMixin,
LoginRequiredMixin,
generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
if request.user.is_superuser:
return self.create(request, *args, **kwargs)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
class LiveClassViewId(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
LoginRequiredMixin,
generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
lookup_field = 'id'
def get(self, request, id=None, format=None):
if id:
return self.retrieve(request)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
def put(self, request, id, format=None):
if request.user.is_superuser:
return self.update(request, id)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
def delete(self, request, id, format=None):
if request.user.is_superuser:
return self.destroy(request, id)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
class ListMentors(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.Mentor.objects.all()
serializer_class = serializers.Mentor_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class ListUserDetails(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.User_details.objects.all()
serializer_class = serializers.User_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
#api endpoints to save and register live classes
class SavedClassView(LoginRequiredMixin, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
serializer_class = serializers.SavedClass_serializer
def get_queryset(self):
user = self.request.user
return models.SavedClass.objects.filter(user=self.request.user.id)
def get(self, request):
return self.list(request)
def post(self, request):
cur_user = self.get_object()
#return self.create(request)
return Response(status=status.HTTP_403_FORBIDDEN)
my serializers.py
from rest_framework import serializers
from . import models
class LiveClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass
fields = '__all__'
class SavedClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.SavedClass
fields = '__all__'
class User_details_serializer(serializers.ModelSerializer):
saved_class = SavedClass_serializer()
class Meta:
model = models.User_details
fields = '__all__'
class LiveClass_details_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass_details
fields = '__all__'
class Mentor_serializer(serializers.ModelSerializer):
class Meta:
model = models.Mentor
fields = '__all__'
In savedClass view in GET request i am rendering all the savedClass Model wherever user in the model matches with the current user , now in POST request i want to create the savedclass row only for the current user and forbids the user from creating a view with different user id
I also needs help in my SavedClass model where whether a user is registered or not can only be decided by the admin
I tries different possible things but not able to do it, i am new to Django so needs help
You can get the logged in user from request.user so something like this should work
def post(self, request):
cur_user = request.user
if cur_user.id == request.data.user:
return self.create(request)
return Response(status=status.HTTP_403_FORBIDDEN)
assuming that only logged in users can call this api

Django redirect, reverse

How can i do it so the user after editing the post doesn't get redirected to homepage but to the detail view of the post they just edited
My views.py
from . models import Post
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DeleteView, UpdateView, CreateView
from django.urls import reverse_lazy
def home(request):
posts = Post.objects.all()
return render(request, 'pages/index.html', {'posts':posts})
def detail(request, slug):
post = Post.objects.get(slug=slug)
return render(request, 'pages/detail.html', {'post':post})
class edit(LoginRequiredMixin, UpdateView):
model = Post
template_name = 'pages/edit.html'
fields = ['title','image','body']
success_url = reverse_lazy('pages:homepage')
def dispatch(self, request, *args, **kwargs):
handler = super().dispatch(request, *args, **kwargs)
user = request.user
post = self.get_object()
if post.author != user:
raise PermissionDenied
return handler
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.db.models.signals import pre_save
from A_Tech_Blog.utils import unique_slug_generator
class Post(models.Model):
title = models.CharField(max_length=300)
slug = models.SlugField(blank=True, null=True, max_length=300)
image = models.ImageField(upload_to='post_images', default='default.jpg')
time_created = models.DateTimeField(auto_now_add=True)
views = models.IntegerField(default=0)
body = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f'{self.title} -- Author={str(self.author)}'
class Meta:
ordering = ['-time_created']
verbose_name_plural = 'Posts'
def get_absolute_url(self):
return reverse('pages:detail', args=(self.slug))
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=Post)
I want to be able to edit the post then get directed to the detail view of the post instead of being redirected to the web app homepage
You can override the get_success_url() method in your view
Something like this should work
class edit(LoginRequiredMixin, UpdateView):
...
# success_url = reverse_lazy('pages:homepage')
def get_success_url(self):
return reverse('pages:detail', args=[self.slug])

IntegrityError at /posts/new/

I am new on this field and i am currently learning django and i come up with this problem. I am working on a project which is a social clone project and this project you can only post when you are in a group and i've encountered this problem when i post. The first post is working fine but the second post i get this error message called IntegrityError i've tried to delete my migrations and database and migrate and makemigrations again but does not fix the problem and now i am stuck and i hope someone will help me. This is the actual error
Posts Models
##########################
## POSTS MODELS.PY FILE ##
##########################
from django.contrib.auth import get_user_model
from django.db import models
from groups.models import Group
from misaka import html
from django.urls import reverse
from django.conf import settings
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.message
def save(self, *args, **kwargs):
self.message_html = html(self.message)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse(
'posts:single',
kwargs={
'username': self.user.username,
'pk': self.pk
}
)
class Meta:
ordering = ['-created_at']
unique_together = ['user', 'group']
Posts Views.py
#########################
## POSTS VIEWS.PY FILE ##
#########################
from django.contrib.auth import get_user_model
from braces.views import SelectRelatedMixin
from django.views import generic
from posts import models, forms
from django.http import Http404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.contrib import messages
User = get_user_model()
class PostList(SelectRelatedMixin, generic.ListView):
model = models.Post
select_related = ('user', 'group')
class UserPost(generic.ListView):
model = models.Post
template_name = 'posts/user_post_list.html'
def get_queryset(self):
try:
self.post_user = User.objects.prefetch_related('posts').get(
username__iexact=self.kwargs.get('username')
)
except User.DoesNotExist:
raise Http404
else:
return self.post_user.posts.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['post_user'] = self.post_user
return context
class PostDetail(SelectRelatedMixin, generic.DetailView):
model = models.Post
select_related = ('user', 'group')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(
user__username__iexact=self.kwargs.get('username')
)
class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):
model = models.Post
fields = ('message', 'group')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
model = models.Post
select_related = ('user', 'group')
success_url = reverse_lazy('posts:all')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self, *args, **kwargs):
messages.success(self.request, ('Post Delete'))
return super().delete(*args, **kwargs)
Groups Models.py
##########################
## GROUPS VIEWS.PY FILE ##
##########################
from django.contrib.auth import get_user_model
from django import template
from django.db import models
from django.utils.text import slugify
from misaka import html
from django.urls import reverse
from django.conf import settings
User = get_user_model()
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
description = models.TextField(blank=True, default='')
description_html = models.TextField(editable=False, blank=True, default='')
members = models.ManyToManyField(User, through='GroupMember')
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
self.description_html = html(self.description)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('groups:single', kwargs={'slug': self.slug})
class Meta:
ordering = ['name']
class GroupMember(models.Model):
group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Meta:
unique_together = ('group', 'user')
Groups Views.py
[![##########################
## GROUPS VIEWS.PY FILE ##
##########################
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from groups.models import Group, GroupMember
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.db import IntegrityError
from django.contrib import messages
from groups import models
class CreateGroup(LoginRequiredMixin, generic.CreateView):
model = Group
fields = ('name', 'description')
class SingleGroup(generic.DetailView):
model = Group
class ListGroups(generic.ListView):
model = Group
class JoinGroup(LoginRequiredMixin, generic.RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')})
def get(self, request, *args, **kwargs):
group = get_object_or_404(Group, slug=self.kwargs.get('slug'))
try:
GroupMember.objects.create(user=self.request.user, group=group)
except IntegrityError:
messages.warning(self.request, (f'Warning, Already A Member Of {group.name}.'))
else:
messages.success(self.request, (f'You Are Now A Member Of {group.name} Group.'))
return super().get(request, *args, **kwargs)
class LeaveGroup(LoginRequiredMixin, generic.RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')})
def get(self, request, *args, **kwargs):
try:
membership = models.GroupMember.objects.filter(
user=self.request.user,
group__slug=self.kwargs.get('slug')
).get()
except models.GroupMember.DoesNotExist:
messages.warning(self.request, ("You Can't Leave This Group Because You Aren't In It."))
else:
membership.delete()
messages.success(self.request, ('You Have Successfully Left This Group.'))
return super().get(request, *args, **kwargs)
Remove unique_together from your Post model. It means that only one Post object can have that particular user and model combination, that is why you are getting the integrity error.
The error which you are getting is all about the unique constraint.
unique_together = ['user', 'group']
Since you have defined in your model the unique_together attribute, you need to have unique rows of the combination for user and group. One user can post only once in a group and you are trying to post in the same group by the same user, that's why you are getting a unique constraint failed error.

django - TemplateDoesNotExist error

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

Categories