You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

views.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from django.shortcuts import render, redirect
  2. from django.utils import timezone
  3. from .forms import NoticeForm
  4. from django.http import JsonResponse, HttpResponse
  5. from .models import Notice
  6. from .serializers import NoticeSerializer
  7. from rest_framework.parsers import JSONParser
  8. from django.views.decorators.csrf import csrf_exempt
  9. from django_eventstream import send_event
  10. def new(request):
  11. if request.method == "POST":
  12. form = NoticeForm(request.POST)
  13. if form.is_valid():
  14. new_notice = Notice(notice_title=form.cleaned_data['title'],
  15. notice_text=form.cleaned_data['text'],
  16. pub_start=form.cleaned_data['start'],
  17. pub_end=form.cleaned_data['end'])
  18. new_notice.save()
  19. send_event('notice', 'message', new_notice.id)
  20. return redirect('index')
  21. context = {'form': NoticeForm()}
  22. return render(request, 'posts/edit.html', context)
  23. def index(request):
  24. notices = Notice.objects.all()
  25. notices = notices.filter(pub_start__lte=timezone.now())
  26. notices = notices.filter(pub_end__gte=timezone.now())
  27. context = {"notices": notices}
  28. return render(request, 'posts/index.html', context)
  29. def delete(request, deleteId=None):
  30. if deleteId !=None:
  31. delNotice = Notice.objects.get(id=deleteId)
  32. if delNotice != None:
  33. delNotice.delete()
  34. return redirect('index')
  35. @csrf_exempt
  36. def notice_list(request):
  37. if request.method == 'GET':
  38. notices = Notice.objects.all()
  39. serializer = NoticeSerializer(notices, many=True)
  40. return JsonResponse(serializer.data, safe=False)
  41. elif request.method == 'POST':
  42. data = JSONParser().parse(request)
  43. serializer = NoticeSerializer(data=data)
  44. if serializer.is_valid():
  45. serializer.save()
  46. return JsonResponse(serializer.data, status=201)
  47. return JsonResponse(serializer.errors, status=400)
  48. @csrf_exempt
  49. def notice_detail(request, id):
  50. try:
  51. notice = Notice.objects.get(id=id)
  52. except Notice.DoesNotExist:
  53. return HttpResponse(status=404)
  54. if request.method == 'GET':
  55. serializer = NoticeSerializer(notice)
  56. return JsonResponse(serializer.data)
  57. elif request.method == 'PUT':
  58. data = JSONParser().parse(request)
  59. serializer = NoticeSerializer(notice, data=data)
  60. if serializer.is_valid():
  61. serializer.save()
  62. return JsonResponse(serializer.data)
  63. return JsonResponse(serializer.errors, status=400)
  64. elif request.method == 'DELETE':
  65. notice.delete()
  66. return HttpResponse(status=204)