我正在使用Django REST框架来提供API服务。我在views.py。中使用了viewset。
我能够在viewset类中定义一个自定义get函数,但是当我定义一个自定义post函数时。它不允许抛出POST方法。
以下代码
from rest_framework.decorators import detail_route
from rest_framework.decorators import list_route
from rest_framework.permissions import IsAuthenticated
from models import movies
from rest_framework import viewsets
from serializers import MoviesSerializer
from rest_framework import filters
from rest_framework.response import Response
class MoviesViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = movies.objects.all()
serializer_class = MoviesSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('status', 'userID','avgRating')
@list_route(methods=['get'])
def movieList(self, request):
print "mm"
recent_users = movies.objects.all()
page = self.paginate_queryset(recent_users)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(recent_users, many=True)
return Response(serializer.data)
@detail_route(methods=['post'], permission_classes=[IsAuthenticated])
def set_password(self, request, pk=None):
print "ms"
======== urls.py
from quickstart.views import MoviesViewSet
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.authtoken import views
router = routers.DefaultRouter()
router.register(r'movies', MoviesViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/', views.obtain_auth_token),
]
============= models.py
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
# Create your models here.
class movies(models.Model):
class Meta:
db_table = 'movies'
shortDesc = models.CharField(max_length=200)
productionYear = models.CharField(max_length=4)
longDesc = models.TextField()
moderatorComments = models.TextField(null=True)
uploaded = models.DateTimeField('date published')
modified = models.DateTimeField('date published')
moderated = models.DateTimeField('date published',null=True)
userID = models.IntegerField(default=0)
private = models.IntegerField(default=0)
avgRating = models.IntegerField(default=0)
ratingCount = models.IntegerField(default=0)
runtime = models.IntegerField(default=0)
moderatorID = models.IntegerField(null=True)
status = models.CharField(max_length=100)
active = models.CharField(max_length=100)
credits = models.CharField(max_length=100)
def __unicode__(self):
return self.shortDesc
class sources(models.Model):
class Meta:
db_table = "sources"
eventID = models.IntegerField(db_column="eventID")
brandID = models.IntegerField(db_column="brandID")
sponsorID = models.IntegerField(db_column="sponsorID")
termsID = models.IntegerField(db_column="termsID")
tripBudget = models.IntegerField(db_column="tripBudget")
name = models.CharField(max_length=40)
webfilename = models.CharField(max_length=50)
status = models.CharField(max_length=50)
hidden = models.CharField(max_length=50)
custom = models.CharField(max_length=50)
instructions = models.TextField()
bgcolor = models.CharField(max_length=10)
startDate = models.DateTimeField('date published')
endDate = models.DateTimeField('date published')
closeDate = models.DateField()
createdDate = models.DateTimeField()
class movieSources(models.Model):
class Meta:
db_table = "movieSources"
movieID = models.ForeignKey(movies, related_name="movieSources", db_column="movieID", primary_key=True)
sourceID = models.ForeignKey(sources, related_name="movieSources",db_column='sourceID',primary_key=True)
def __unicode__(self):
return "Event: %s" %(self.sourceID.eventID) + "," + "Source: %s" % (self.sourceID.id)
======
curl -X post http://127.0.0.1:8000/movies/set_password/ -H 'Authorization: Token 176307c4203472abda4c60a115ad3951b0301710'
答案 0 :(得分:1)
您的@detail_route
应该适用于单个对象,实际上您正在创建以下网址:
/movies/123/set_password/
因此,要么更正客户端上的网址,要么更改查询集上的内容而不是单个对象,请使用@list_route
修饰您的视图。