python - 发布请求 Django REST 框架

标签 python django rest post django-rest-framework

这是我的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)

这是我的 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'), 
)

这是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')

最后这是 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)

现在如何在没有 UI 的情况下使用 Django Rest 浏览器在 Django Rest 中编写 POST 请求。 我想做一个 POST 请求来使用 url 捕获调查中的选择,就像我为 get 所做的那样。这可能吗?

最佳答案

在 views.py 中添加一个像这样的新类:

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)

并在 urls.py 中添加如下新行:

url(r'^create-survey/$', SurveyAPIView.as_view(),name ='create-survey') ,

关于python - 发布请求 Django REST 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593014/

相关文章:

python - 使用 Django REST 框架进行序列化/反序列化的不同序列化器

python - 需要从 simple.tag 制作模板标签

python - django Rest框架和模型继承

python - 在 Windows 中安装 MATLAB 试用版时安装适用于 Python 的 matlab 引擎

python正则表达式删除匹配的括号文件

python - Sphinx 找不到我的 python 文件。说 'no module named ...'

rest - 使用 Http 406 返回什么?

java - 如何使用 Gson 处理具有时间戳的 Json 响应? java.lang.IndexOutOfBoundsException

api - 使用 VersionOne 的 RESTful API 重新排列故事

python - 使用像 PMI 这样的 bigram_measures 时何时删除停用词?