标签:efi poi model 序列化 key nts represent 代码 ted
owner = models.ForeignKey(‘auth.User‘,related_name=‘myLesson‘,on_delete=models.CASCADE) highlighted = models.TextField()
from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight def save(self,*args,**kwargs): """ Use the ‘pygments‘ library to created a highlighted HTML representation of code myLesson """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and ‘table‘ or False options = self.title and {‘title‘:self.title} or {} formatter = HtmlFormatter(style=self.style,linenos=linenos, full=True,**kwargs) self.highlighted = highlight(self.code,lexer,fomatter) super(MyLesson,self).save(*args,**kwargs)
from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): myLesson = serializers.PrimaryKeyRelatedField(many=True,queryset=MyLesson.objects.all()) class Meta: model = User fields = (‘id‘,‘username‘,‘myLesson‘)
from django.contrib.auth.models import User from myLesson.serializers import MyLessonSerializer,UserSerializer class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer
最后添加这些views到API中,修改urls.py:
url(r‘^users/$‘,views.UserList.as_view()), url(r‘^users/(?P<pk>[0-9]+)/$‘,views.UserDetail.as_view()),
def perform_create(self,serializer): serializer.save(owner=self.request.user)
在create方法中传递owner field,还有我们要创建的数据
class MyLessonSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source=‘owner.username‘) class Meta: model = MyLesson fields = (‘id‘,‘title‘,‘code‘,‘linenos‘,‘language‘,‘style‘,‘owner‘)
ReadOnlyField非常有趣,source参数用来植入一个field,可以用任何Serializer类中的属性,ReadOnlyField可以用CharField(read_only=True)代替
from rest_framework import permissions permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
from django.conf.urls import include url(r‘^api-auth/‘, include(‘rest_framework.urls‘,namespace=‘rest_framework‘)),
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self,request,view,obj): #Read permissions are allowed to any request, #so we`ll always allow GET,HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True #Write permissions are only allowed to the owner of the snippet return obj.owner == request.user
from myLesson.permissions import IsOwnerOrReadOnly permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)
django-rest-framework学习之Authentication & Permissions--2017年4月14日
标签:efi poi model 序列化 key nts represent 代码 ted
原文地址:http://www.cnblogs.com/jingbostar/p/6710215.html