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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from django.contrib.auth.decorators import login_required
  2. from django.shortcuts import render, redirect
  3. from django.views.decorators.csrf import csrf_exempt
  4. from rest_framework.parsers import JSONParser
  5. from posts.forms import NoticeForm
  6. from posts.serializers import NoticeSerializer
  7. from.models import Notice
  8. from django.utils import timezone
  9. from django.http import HttpResponse, JsonResponse
  10. def index(request):
  11. notices= Notice.objects.all()
  12. notices= notices.filter(pub_start__lte=timezone.now())
  13. notices= notices.filter(pub_end__gte= timezone.now())
  14. context={"notices":notices}
  15. return render(request, 'posts/notice.html', context)
  16. @login_required
  17. def new(request):
  18. if request.method == "POST":
  19. form = NoticeForm(request.POST)
  20. if form.is_valid():
  21. newNotice = Notice(notice_title=form.cleaned_data['title'],
  22. notice_text=form.cleaned_data['text'],
  23. pub_start=form.cleaned_data['start'],
  24. pub_end=form.cleaned_data['end'])
  25. newNotice.save()
  26. return redirect('index')
  27. context = {'form': NoticeForm()}
  28. return render(request, 'posts/edit.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=201)
  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)