This is my views.py
from rest_framework import generics, permissions
from .models import Survey,Response
from .serialize import SurveySerializer,ResponseSerializer,SurveySerializerQuestion
from rest_framework.decorators import api_view
class SurveyList(generics.ListAPIView):
model = Survey
serializer_class = SurveySerializerQuestion
def get_queryset(self):
return Survey.objects.all()
class SurveyListByID(generics.ListAPIView):
model = Survey
serializer_class = SurveySerializer
def get_queryset(self):
survey_id = self.kwargs['survey_id']
return Survey.objects.filter(survey_id = survey_id)
class ResponseList(generics.ListAPIView):
model = Response
serializer_class = ResponseSerializer
def get_queryset(self):
survey_id = self.kwargs['survey_id']
return Response.objects.filter(survey_id = survey_id)
This is my urls.py
from django.conf.urls import patterns, include, url
from views import SurveyList,SurveyListByID,ResponseList
urlpatterns = patterns('',
url(r'^surveys/$', SurveyList.as_view(),name ='survey-list') ,
url(r'^surveys/(?P<survey_id>[0-9]+)/$', SurveyListByID.as_view(),name ='survey-list-by-id'),
url(r'^response/(?P<survey_id>[0-9]+)/$', ResponseList.as_view(),name ='response-list'),
)
This is serialize.py
from rest_framework import serializers
from .models import Employee,Survey,EmployeeSurvey,Response
class SurveySerializer(serializers.ModelSerializer):
class Meta:
model = Survey
fields = ('survey_id', 'question', 'choice1','choice2')
class SurveySerializerQuestion(serializers.ModelSerializer):
class Meta:
model = Survey
fields = ('survey_id', 'question')
class ResponseSerializer(serializers.ModelSerializer):
class Meta:
model = Response
fields = ('id','survey_id','choice1_count','choice2_count')
finally this is models.py
import re
from django.db import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
def alphanumeric_test(val):
if not re.match('^[0-9a-zA-Z]*$', val):
raise ValidationError('Only alphanumeric characters are allowed.')
def alphabetic_test(val):
if not re.match('^[a-zA-Z]*$', val):
raise ValidationError('Please enter alphabetic value.')
class Survey(models.Model):
survey_id = models.AutoField(primary_key=True)
question = models.CharField(max_length = 300)
choice1 = models.CharField(max_length = 100)
choice2 = models.CharField(max_length = 100)
def __unicode__(self):
return u'%s %s %s' % (self.question,self.choice1,self.choice2)
class Response(models.Model):
survey_id = models.ForeignKey(Survey, blank=True, null=True, on_delete=models.SET_NULL)
choice1_count = models.IntegerField()
choice2_count = models.IntegerField()
def __unicode__(self):
return u'%s %s %s' % (self.survey_id,self.choice1_count,self.choice2_count)
Now how do I write a POST request in Django Rest without UI and using the Django Rest Browser.
I want to do a POST request to capture the choice in the survey using a url like I did for get.Is that possible?
In views.py add a new class like this:
class SurveyAPIView(APIView):
def post(self, request, format=None):
serializer = SurveySerializer(request.data)
if serializer.is_valid():
instance = serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
and in urls.py add a new line like:
url(r'^create-survey/$', SurveyAPIView.as_view(),name ='create-survey') ,
Related
When I try to retrieve all data from my REST API I get them correctly except from one field, that is the field 'name' from Skill class. Instead of the 'name' I get only its id. Can you help me to resolve this?----------------------------------------------
here is the output
Here is the code:
models.py
from django.db import models
from django.forms import ImageField
from django.utils.text import slugify
class Skill(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Project(models.Model):
title = models.CharField(max_length=200)
sub_title = models.CharField(max_length=200, null=True, blank=True)
front_page = models.ImageField(null=True, blank=True, upload_to="images", default="broken-image.png")
body = models.TextField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
skills = models.ManyToManyField(Skill, null=True)
slug = models.SlugField(null=True, blank=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if self.slug == None:
slug = slugify(self.title)
has_slug = Project.objects.filter(slug=slug).exists()
count = 1
while has_slug:
count += 1
slug = slugify(self.title) + '-' + str(count)
has_slug = Project.objects.filter(slug=slug).exists()
self.slug = slug
super().save(*args, **kwargs)
serializers.py
from rest_framework import serializers
from project.models import Project, Skill
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from project.models import Project, Skill
from .serializers import ProjectSerializer
from rest_framework import status
from django.shortcuts import get_object_or_404
#api_view(['GET'])
def getData(request):
project = Project.objects.all()
serializer = ProjectSerializer(project, many=True)
return Response(serializer.data)
#api_view(['POST'])
def create(request):
serializer= ProjectSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
#api_view(['POST'])
def update(request, pk):
item = Project.objects.get(pk=pk)
serializer = ProjectSerializer(instance=item, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
#api_view(['DELETE'])
def delete(request, pk):
item = get_object_or_404(Project, pk=pk)
item.delete()
return Response(status=status.HTTP_202_ACCEPTED)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.getData),
path('create/', views.create),
path('update/<int:pk>/', views.update),
path('<int:pk>/delete/', views.delete),
]
Use a SlugRelatedField [drf-doc] to specify that you want to use the name of the skills, so:
from rest_framework import serializers
from project.models import Project, Skill
class ProjectSerializer(serializers.ModelSerializer):
skills = serializers.SlugRelatedField(
many=True, slug_field='name', queryset=Skill.objects.all()
)
class Meta:
model = Project
fields = '__all__'
The nice thing of such SlugRelatedField is that this can work bidrectional: not only can you serialize data, but you can also use it to specify skills and thus create or update Projects.
You need to provide a SkillSerializer and refer to it in your ProjectSerializer. Also, it is better to specify the fields you want in your serializers explicitly, as __all__ may expose the fields you don't want to expose or cause unwanted database queries.
https://www.django-rest-framework.org/api-guide/relations/#nested-relationships
Problem: I trying to path like this --> path('Image/<str>', views.getImage, name='imageCategory'),
to get image filter by category --> http://127.0.0.1:8000/Image/TV
#-->Model.py
from django.db import models
class Post(models.Model):
Topic = models.CharField(max_length=250, default='')
Desc = models.CharField(max_length=750, default='')
Link = models.TextField(default='')
def __str__(self):
return str(self.Topic)
class Category(models.Model):
categoryName = models.CharField(max_length=50, default='')
def __str__(self):
return str(self.categoryName)
class PostImage(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, null=True, related_name='post_name')
category = models.ForeignKey(
Category, on_delete=models.CASCADE, null=True, related_name='category_name')
images = models.FileField(upload_to='images/')
def __str__(self):
return str(self.post)
#-->Serializer.py
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import Post, PostImage
class BlogSerializer(ModelSerializer):
class Meta:
model = Post
fields = '__all__'
class ImageSerializer(ModelSerializer):
topic_link = serializers.CharField(source='post.Link', read_only=True)
Category = serializers.CharField(source='category', read_only=True)
class Meta:
model = PostImage
fields = '__all__'
#-->view.py
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Post, PostImage
from .Serializer import BlogSerializer, ImageSerializer
# Create your views here.
#api_view(['GET'])
def getNames(request):
Blog = Post.objects.all()
serializer = BlogSerializer(Blog, many=True)
return Response(serializer.data)
#api_view(['GET'])
def getName(request, pk):
Blog = Post.objects.get(id=pk)
serializer = BlogSerializer(Blog, many=False)
return Response(serializer.data)
#my problem part
#api_view(['GET'])
def getImage(request):
image = PostImage.objects.get(Category=request.Category)
serializer = ImageSerializer(image, many=True)
return Response(serializer.data)
#-->urls.py
from django.urls import path
from . import views
urlpatterns = [
path('blogs/', views.getNames, name='blog'),
path('blogs/<pk>', views.getName, name='blog'),
path('Image/', views.getImage, name='image'),
path('Image/<str>', views.getImage, name='imageCategory'),
]
First, you need to set the parameter name in urls.py.
urlpatterns = [
...
path('Image/', views.getImages, name='image'),
path('Image/<str:category>', views.getImage, name='imageCategory'),
]
Here the category should be the categoryName value of the Category model.
Next, in views.py, you need to pass that parameter to the getImage function.
And also you need to add getImages function for the case of no category.
#api_view(['GET'])
def getImage(request, category):
image = PostImage.objects.filter(category__categoryName=category)
serializer = ImageSerializer(image, many=True)
return Response(serializer.data)
#api_view(['GET'])
def getImages(request):
image = PostImage.objects.all()
serializer = ImageSerializer(image, many=True)
return Response(serializer.data)
I am trying to make a dynamic search but cant seem to filter queryset by slug. I have tried just about everything and went through stackoverflow questions and nothing seems to solve it. I have tried changing the keyword to "id" and "category" and I get a result but not on slug.
Here is the error/no queryset I received.
This is the filter I made for authors which seems to work.
Here is the code, Please inform if I need to provide more code to understand the problem as this is my first question here. Thanks!
blog_api/views.py
from rest_framework import generics
from blog.models import Post
from .serializers import PostSerializer
from rest_framework.permissions import SAFE_METHODS, IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission, IsAdminUser, DjangoModelPermissions
from rest_framework import viewsets
from rest_framework import filters
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
class PostUserWritePermission(BasePermission):
message = 'Editing posts is restricted to the author only.'
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
return obj.author == request.user
class PostList(generics.ListAPIView):
permission_classes = [IsAuthenticated]
# queryset = Post.objects.all()
serializer_class = PostSerializer
def get_queryset(self):
user = self.request.user
return Post.objects.filter(author=user)
class PostDetail(generics.RetrieveAPIView, PostUserWritePermission):
# permission_classes = [PostUserWritePermission]
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_queryset(self):
item = self.kwargs["pk"]
print(item)
return Post.objects.filter(slug=item)
blog_api/urls.py
from .views import PostList, PostDetail
from django.urls import path
from rest_framework.routers import DefaultRouter
app_name = 'blog_api'
# router = DefaultRouter()
# router.register('', PostList, basename='post')
# urlpatterns = router.urls
urlpatterns = [
path('posts/<str:pk>/', PostDetail.as_view(), name='detail_create'),
path('', PostList.as_view(), name='list_create'),
]
blog/models.py
from django.db import models
from django.conf import settings
from django.utils import timezone
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
class PostObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status="published")
options = (
("draft", "Draft"),
("published", "Published"),
)
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
title = models.CharField(max_length=250)
excerpt = models.TextField(null=True)
content = models.TextField()
slug = models.SlugField(max_length=250, unique_for_date="published")
published = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="blog_post")
status = models.CharField(max_length=10, choices=options, default="published")
objects = models.Manager()
post_objects = PostObjects()
class Meta:
ordering = ["-published"]
def __str__(self):
return self.title
in your PostDetail class in blog_api/views.py file, instead of overriding get_queryset method, override get_object method, like this
def get_object(self, queryset=None, **kwargs):
item = self.kwargs.get('pk')
return get_object_or_404(Post.objects.filter(slug=item))
trying to add a post to DRF which takes the information of USER and TIME automatically, But this is the error which pops up when tried to add a Post.
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length = 200)
description = models.CharField(max_length = 2000)
date_posted = models.DateTimeField(default = timezone.now)
author = models.ForeignKey(User , on_delete = models.CASCADE)
def __str__(self):
return self.title
Views.py:
class PostViewSet(ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
authentication_classes = [TokenAuthentication,SessionAuthentication]
def create(self, request):
obj = Post()
obj.title = request.data['title']
obj.description = request.data['description']
obj.date_posted = request.data['date_posted']
obj.user = request.user
obj.save()
return Response(status=status.HTTP_201_CREATED)
serializer.py:
from rest_framework import serializers
from django.contrib.auth.models import User
from . models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'title','description','date_posted','author')
I am having problems with reproducing example from Julia Elman's book
models.py
class Sprint(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
description = models.TextField(blank=True, default='')
end = models.DateField(unique=True)
def __str__(self):
return self.name or _('Sprint ending %s') % self.end
serializer.py
from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework.reverse import reverse
from .models import Sprint, Task
User = get_user_model()
class SprintSerializer(serializers.ModelSerializer):
links = serializers.SerializerMethodField('get_links')
class Meta:
model = Sprint
fields = ('id', 'name', 'description', 'end', 'links',)
def get_links(self, obj):
request = self.context['request']
return {'self': reverse('sprint-detail',kwargs={'pk': obj.pk},request=request),}
views.py
from django.contrib.auth import get_user_model
from rest_framework import authentication, permissions, viewsets
from .models import Sprint,Task
from .serializers import SprintSerializer,TaskSerializer, UserSerializer
User = get_user_model()
class DefaultsMixin(object):
authentication_classes = (authentication.BasicAuthentication,authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
paginate_by = 25
paginate_by_param = 'page_size'
max_paginate_by = 100
class SprintViewSet(DefaultsMixin, viewsets.ModelViewSet):
queryset = Sprint.objects.order_by('end')
serializer_class = SprintSerializer
I try to see repr from shell
from board.serializers import SprintSerializer
>>> s = SprintSerializer()
>>> print (repr(s))
But I have problem
AssertionError: The field 'links' was declared on serializer SprintSerializer, but has not been included in the 'fields' option.
My DRF
print (rest_framework.VERSION)
3.8.2
How to debug this issue?
Yes,what Alexandr Tartanov suggested works fine.We need to pass arguments with source
links = serializers.SerializerMethodField(source='get_links')
Output
print (repr(s))
SprintSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(allow_blank=True, max_length=100, required=False)
description = CharField(allow_blank=True, required=False, style={'base_template': 'textarea.html'})
end = DateField(validators=[<UniqueValidator(queryset=Sprint.objects.all())>])
links = SerializerMethodField(source='get_links')