标签:hide bsp lap let 一个 migrate ural read view
https://q1mi.github.io/Django-REST-framework-documentation/tutorial/4-authentication-and-permissions_zh/
1. models.py 表里面加入一列 “operater", 并且重新migrate
from django.db import models class Publisher(models.Model): name = models.CharField(max_length=32, verbose_name="Publisher Name", unique=True) address = models.CharField(max_length=128, verbose_name="Publisher Address") operator = models.ForeignKey("auth.User", on_delete=models.CASCADE) def __str__(self): return self.name class Meta: verbose_name = "Table Publisher" verbose_name_plural = verbose_name
2. serializers.py 里面需要再添加一个field, 并且可以对输出进行重写。
from rest_framework import serializers from helloworld.models import Publisher class PublisherSerializer(serializers.ModelSerializer): operator = serializers.ReadOnlyField(source="operator.username") class Meta: model = Publisher fields = ( "id", "name", "address", "operator" )
3. 新建文件 permissions.py 自定义权限
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ only allow owner to update """ def has_object_permission(self, request, view, obj): # for GET, HEAD, OPTINOS if request.method in permissions.SAFE_METHODS: return True return obj.operator == request.user
4. views.py 针对新的新权限以及列进行调整。
from rest_framework import permissions from helloworld.permissions import IsOwnerOrReadOnly class PublisherList(generics.ListCreateAPIView): queryset = Publisher.objects.all() serializer_class = PublisherSerializer # 新建内容 permissions_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly) # 针对创建时,进行重写某个方法,保证特殊列的写入 def perform_create(self, serializer): serializer.save(operator=self.request.user) class PublisherDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Publisher.objects.all() serializer_class = PublisherSerializer # 新建内容 permissions_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)
django rest frame work 初步使用 >> 认证权限
标签:hide bsp lap let 一个 migrate ural read view
原文地址:https://www.cnblogs.com/shuo-yang0459/p/9514333.html