if user.user_permissions.filter(codename=‘use_tool’).exists():
print "True"
# myapp/models.py
from django.contrib.auth.models import User
from django.db import models
class Post(models.Model):
content = models.CharField(max_length=225)
posted_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
# myapp/serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Post
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name')
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('content', 'posted_at')
class MyMainSerializer(serializers.Serializer):
# В аргументах для полей указываются валидаторы
someVar = serializers.IntegerField(max_value=127)
someAnotherVar = serializers.CharField(allow_blank=True)
currentUser = serializers.SerializerMethodField('get_user')
lastPostsInForum = serializers.SerializerMethodField('get_posts')
# Дополнительные валидаторы можно определить отдельно
def validate_someVar(self, value):
#some validation for someVar
if value % 2:
raise serializers.ValidationError(
detail='someVar should be even'
)
return value
def validate_someAnotherVar(self, value):
if 'Something' in value:
raise serializers.ValidationError(
detail='someAnotherVar can\'t contain "Something"'
)
return value
def get_user(self, obj):
user = self.context['request'].user
return UserSerializer(user).data
def get_posts(self, obj):
user = self.context['request'].user
last_posts = Post.objects.filter(user=user).order_by('-posted_at')[:5]
return PostSerializer(last_posts, many=True).data
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import MyMainSerializer
@api_view(['GET', 'POST'])
def my_view(request):
if request.method == 'GET':
someVar = 20
someAnotherVar = 'HelloWorld'
# Надо передать request в контекст сериалайзера чтобы поля
# для пользователя и постов корректно работали.
serializer = MyMainSerializer(
data={'someVar': someVar, 'someAnotherVar': someAnotherVar},
context={'request': request}
)
if serializer.is_valid():
return Response(serializer.data)
elif request.method == 'POST':
serializer = MyMainSerializer(data=request.data)
if serializer.is_valid():
data = serializer.data
someVar = data.get('someVar')
someAnotherVar = data.get('someAnotherVar')
# do something with variables here
return Response({'message': 'ok'}, status=status.HTTP_200_OK)
return Response({'message': 'not ok'}, status=status.HTTP_400_BAD_REQUEST)
from django.http import HttpResponse
def index(request):
posts = Post.objects.all().order_by('-date_pub').count()
return HttpResponse(posts)
from django.shortcuts import render
def index(request):
posts = Post.objects.all().order_by('-date_pub').count()
return render(request, '/путь до шаблона/', {'posts_count': posts})
python xml to xlsx