from rest_framework import status, permissions from rest_framework.decorators import permission_classes from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from django.contrib.auth import login, logout from django.contrib.auth.backends import ModelBackend from workreport.models import DailyReport from workreport.serializer import DailyReportSerializer class DailyReportViews(APIView): def get(self, request): data = DailyReport.objects.values('title', 'content', 'create_at', 'create_by', 'id') return Response(data=data, status=status.HTTP_200_OK) def post(self, request): data = request.data report = DailyReport(title=data['title'], content=data['content'], create_by_id=data['create_by_id']) report.save() return Response(status=status.HTTP_201_CREATED) class ReportViews(ModelViewSet): queryset = DailyReport.objects.all() serializer_class = DailyReportSerializer # search_fields '^'开始搜索。'='完全匹配。'@'全文搜索。(当前仅支持Django的MySQL后端。)'$'正则表达式搜索。 filter_fields = {'title': ['exact']} @permission_classes((permissions.AllowAny,)) class LoginView(APIView): def post(self, request): data = request.data user = ModelBackend().authenticate(username=data['username'], password=data['password'], request=request) if user is None: return Response(data={'msg': '用户名或密码不正确'}, status=status.HTTP_404_NOT_FOUND) else: login(request, user=user, backend='django.contrib.auth.backends.ModelBackend') return Response(status=status.HTTP_200_OK) class LogoutView(APIView): def post(self, request): logout(request) return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)