views.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from django.contrib.auth import login, logout
  2. from django.contrib.auth.backends import ModelBackend
  3. # Create your views here.
  4. from rest_framework import status, permissions
  5. from rest_framework.decorators import permission_classes
  6. from rest_framework.response import Response
  7. from rest_framework.views import APIView
  8. from rest_framework.viewsets import ModelViewSet
  9. from workreport.models import DailyRreport
  10. from workreport.serializer import DailyReportSerializer
  11. class ReportView(APIView):
  12. def get(self, request):
  13. data = DailyRreport .objects.values('title', 'content', 'create_at', 'create_by', 'id')
  14. return Response(data=data, status=status.HTTP_200_OK)
  15. def post(self, request):
  16. # pass
  17. data = request.data
  18. dailyRreport = DailyRreport(title = data['title'],
  19. content = data['content'],
  20. create_by_id = data['create_by_id'])
  21. dailyRreport.save()
  22. return Response(status = status.HTTP_201_CREATED)
  23. def delete(self, request):
  24. pass
  25. class DailyReportView(ModelViewSet):
  26. queryset = DailyRreport.objects.all()
  27. serializer_class = DailyReportSerializer
  28. filter_fields = {'title': ['exact']}
  29. def update(self, request, *args, **kwargs):
  30. kwargs['partial'] = True
  31. return super().update(request, *args, **kwargs)
  32. @permission_classes((permissions.AllowAny,))
  33. class LoginView(APIView):
  34. def post(self, request):
  35. data = request.data
  36. user = ModelBackend().authenticate(username=data['username'], password=data['password'],request=request)
  37. # user = authenticate(username=data['username'], password=data['password'], request=request)
  38. if user is None:
  39. return Response(data={'msg': '用户名或密码不正确'}, status=status.HTTP_404_NOT_FOUND)
  40. else:
  41. login(request, user=user, backend='django.contrib.auth.backends.ModelBackend')
  42. # login(request, user=user)
  43. return Response(status=status.HTTP_200_OK, data={'user_id': user.id})
  44. class LogoutView(APIView):
  45. def post(self, request):
  46. logout(request)
  47. return Response(data={'msg': 'logout success!'}, status=status.HTTP_200_OK)