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.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. def new(request):
  10. if request.method == "POST":
  11. form = NoticeForm(request.POST)
  12. if form.is_valid():
  13. newNotice = Notice(notice_title=form.cleaned_data['title'],
  14. notice_text=form.cleaned_data['text'],
  15. pub_start=form.cleaned_data['start'],
  16. pub_end=form.cleaned_data['end'])
  17. newNotice.save()
  18. return redirect('index')
  19. context = {'form': NoticeForm()}
  20. return render(request, 'posts/edit.html', context)
  21. def index(request):
  22. notices = Notice.objects.all()
  23. notices = notices.filter(pub_start__lte=timezone.now())
  24. notices = notices.filter(pub_end__gte=timezone.now())
  25. context = {"notices": notices}
  26. return render(request, 'posts/index.html', context)
  27. def delete(request, deleteId=None):
  28. if deleteId !=None:
  29. delNotice = Notice.objects.get(id=deleteId)
  30. if delNotice != None:
  31. delNotice.delete()
  32. return redirect('index')
  33. @csrf_exempt
  34. def notice_list(request):
  35. if request.method == 'GET':
  36. notices = Notice.objects.all()
  37. serializer = NoticeSerializer(notices, many=True)
  38. return JsonResponse(serializer.data, safe=False)
  39. elif request.method == 'POST':
  40. data = JSONParser().parse(request)
  41. serializer = NoticeSerializer(data=data)
  42. if serializer.is_valid():
  43. serializer.save()
  44. return JsonResponse(serializer.data, status=201)
  45. return JsonResponse(serializer.errors, status=400)
  46. @csrf_exempt
  47. def notice_detail(request, id):
  48. try:
  49. notice = Notice.objects.get(id=id)
  50. except Notice.DoesNotExist:
  51. return HttpResponse(status=404)
  52. if request.method == 'GET':
  53. serializer = NoticeSerializer(notice)
  54. return JsonResponse(serializer.data)
  55. elif request.method == 'PUT':
  56. data = JSONParser().parse(request)
  57. serializer = NoticeSerializer(notice, data=data)
  58. if serializer.is_valid():
  59. serializer.save()
  60. return JsonResponse(serializer.data)
  61. return JsonResponse(serializer.errors, status=400)
  62. elif request.method == 'DELETE':
  63. notice.delete()
  64. return HttpResponse(status=204)