我正在开发一个简单的博客项目来学习django rest框架。我正在按照教程进行操作,但有些事情似乎没有按预期工作。
这里我试图列出,创建,更新,检索和销毁对象。但是,我只能列出并创建。其他三个功能没有按预期工作。
以下是我的应用: -
models.py
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length = 30)
author = models.CharField(max_length = 50)
tags = models.CharField(max_length = 10)
post = models.TextField(max_length = 100)
class Meta:
ordering = ('title',)
def __str__(self):
return self.title
serializers.py
from rest_framework import serializers
from loginapp.models import *
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.views import APIView
from rest_framework import generics
from loginapp.models import *
from loginapp.serializers import *
# Create your views here.
class BlogListCreate(generics.ListCreateAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
class BlogDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
urls.py
from django.conf.urls import url
from loginapp import views
urlpatterns = [
url(r'^loginapp/(?P<pk>[0-9]+)/', views.BlogDetail.as_view()),
url(r'^loginapp/', views.BlogListCreate.as_view()),
]
你可以帮我解决这个问题吗?
注意:页面中没有可用于更新/删除/检索的选项。 即使我通过url传递id值,它也不会检索预期的记录。抱歉,我无法附加HTML页面。
答案 0 :(得分:2)
如果您想要所有CRUD功能,请将views.py
更改为
from rest_framework import viewsets
from rest_framework import permissions
class BlogViewSet(viewsets.ModelViewSet):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
# POST/PUT/PATCH will by default not be enabled in DRF ui
# unless you are logged in so set permission classes to AllowAny or
# empty(permission_classes = ()), Do not do it in Production
permission_classes = (permissions.AllowAny,)
和urls.py
到
from loginapp.view import BlogViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'loginapp', BlogViewSet)
urlpatterns = [
url(r'^', router.urls),
]