navigation.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from django.views.generic import View
  5. from libs import json_response, JsonParser, Argument
  6. from apps.home.models import Navigation
  7. import json
  8. class NavView(View):
  9. def get(self, request):
  10. navs = Navigation.objects.all()
  11. return json_response([x.to_view() for x in navs])
  12. def post(self, request):
  13. form, error = JsonParser(
  14. Argument('id', type=int, required=False),
  15. Argument('title', help='请输入导航标题'),
  16. Argument('desc', help='请输入导航描述'),
  17. Argument('logo', help='请上传导航logo'),
  18. Argument('links', type=list, filter=lambda x: len(x), help='请设置导航链接'),
  19. ).parse(request.body)
  20. if error is None:
  21. form.links = json.dumps(form.links)
  22. if form.id:
  23. Navigation.objects.filter(pk=form.id).update(**form)
  24. else:
  25. nav = Navigation.objects.create(**form)
  26. nav.sort_id = nav.id
  27. nav.save()
  28. return json_response(error=error)
  29. def patch(self, request):
  30. form, error = JsonParser(
  31. Argument('id', type=int, help='参数错误'),
  32. Argument('sort', filter=lambda x: x in ('up', 'down'), required=False),
  33. ).parse(request.body)
  34. if error is None:
  35. nav = Navigation.objects.filter(pk=form.id).first()
  36. if not nav:
  37. return json_response(error='未找到指定记录')
  38. if form.sort:
  39. if form.sort == 'up':
  40. tmp = Navigation.objects.filter(sort_id__gt=nav.sort_id).last()
  41. else:
  42. tmp = Navigation.objects.filter(sort_id__lt=nav.sort_id).first()
  43. if tmp:
  44. tmp.sort_id, nav.sort_id = nav.sort_id, tmp.sort_id
  45. tmp.save()
  46. nav.save()
  47. return json_response(error=error)
  48. def delete(self, request):
  49. form, error = JsonParser(
  50. Argument('id', type=int, help='参数错误')
  51. ).parse(request.GET)
  52. if error is None:
  53. Navigation.objects.filter(pk=form.id).delete()
  54. return json_response(error=error)