from django.contrib.auth import login, logout from django.contrib.auth.backends import ModelBackend # Create your views here. 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 workreport.models import DailyRreport from workreport.serializer import DailyReportSerializer class ReportView(APIView): def get(self, request): data = DailyRreport .objects.values('title', 'content', 'create_at', 'create_by', 'id') return Response(data=data, status=status.HTTP_200_OK) def post(self, request): # pass data = request.data dailyRreport = DailyRreport(title = data['title'], content = data['content'], create_by_id = data['create_by_id']) dailyRreport.save() return Response(status = status.HTTP_201_CREATED) def delete(self, request): pass class DailyReportView(ModelViewSet): queryset = DailyRreport.objects.all() serializer_class = DailyReportSerializer filter_fields = {'title': ['exact']} def update(self, request, *args, **kwargs): kwargs['partial'] = True return super().update(request, *args, **kwargs) @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) # user = 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') # login(request, user=user) return Response(status=status.HTTP_200_OK, data={'user_id': user.id}) class LogoutView(APIView): def post(self, request): logout(request) return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)