MEIM_LSG/posts/views.py
2018-12-17 22:27:24 +01:00

88 lines
3.0 KiB
Python

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from datetime import timedelta
from django.utils import timezone
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from posts.models import Notice
from posts.forms import NoticeForm
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from posts.serializers import NoticeSerializer
# Create your views here.
#Titel und die Texte aller Meldungen, deren Veröffentlichungsdatum vor und der Endedatum nach dem aktuellen Datum liegt.
def home(request, value=""):
now = timezone.now()
notices = Notice.objects.all()
display_notices = list()
for notice in notices:
if notice.pub_start < now and notice.pub_end > now:
display_notices.append(notice)
context = {
"title": "Beboop",
"notices": display_notices
}
return render(request, 'index.html', context)
@login_required
def new(request):
if request.method == "POST":
form = NoticeForm(request.POST)
if form.is_valid():
newNotice = Notice(notice_title=form.cleaned_data['title'],
notice_text=form.cleaned_data['text'],
pub_start=form.cleaned_data['start'],
pub_end=form.cleaned_data['end'])
newNotice.save()
return redirect('index')
context = {'form': NoticeForm()}
return render(request, 'edit.html', context)
@staff_member_required
def delete(request, value):
notice = Notice.objects.get(id = value)
notice.delete()
return redirect('index')
@csrf_exempt
def notice_list(request):
if request.method == "GET":
notices = Notice.objects.all()
serializer = NoticeSerializer(notices, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == "POST":
data = JSONParser().parse(request)
serializer = NoticeSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
return HttpResponse(status=405)
@csrf_exempt
def notice_detail(request, id):
try:
notice = Notice.objects.get(id=id)
except:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = NoticeSerializer(notice)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = NoticeSerializer(notice, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
notice.delete()
return HttpResponse(status=204)
return HttpResponse(status=405)