rm -f tmp.db db.sqlite3
rm -r snippets/migrations
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField()
def save(self, *args, **kwargs):
"""
利用pygments,创建高亮的html文本呈现code块
"""
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, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
class Meta:
model = User
fields = ('id', 'username', 'snippets')
# snippets为反向引用,不会被默认包含,所以需要添加显示字段
from django.contrib.auth.models import User
from snippets.serializers import UserSerializer
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P[0-9]+)/$' , views.UserDetail.as_view()),
# 通过重写perform_create()方法
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
添加一行,另外在meta类中也要添加’owner’字段
# 只被用于序列化呈现,而不会被用于更新模型实例
owner = serializers.ReadOnlyField(source='owner.username')
from rest_framework import permissions
# 在SnippetList and SnippetDetail视图函数类中添加
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
urlpatterns += [
# 前面正则表达式,可以随便怎么写,但是namespace,必须要是'rest_framework'
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
设置权限只允许创建者编辑
"""
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.
# 为不同的请求设置权限,GET, HEAD or OPTIONS 为安全请求
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 snippets.permissions import IsOwnerOrReadOnly
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
(SessionAuthentication and BasicAuthentication)