from django.shortcuts import render, redirect from .models import Notice from django.utils import timezone from .forms import NoticeForm from django.contrib.auth.decorators import login_required from django.contrib import messages @login_required def new(request): if request.method == 'POST': form = NoticeForm(request.POST) if form.is_valid(): notice = Notice() notice.notice_title = form.cleaned_data['notice_title'] notice.notice_text = form.cleaned_data['notice_text'] notice.pub_start = form.cleaned_data['pub_start'] notice.pub_end = form.cleaned_data['pub_end'] notice.user_id = request.user.id notice.save() messages.success(request, f"Neue Nachricht erstellt") return redirect('index') else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") context = {'form': NoticeForm()} return render(request, 'polls/edit.html', context) @login_required def delete(request, deleteId=None): if deleteId is not None: try: notice = Notice.objects.get(pk=deleteId) if request.user.id == notice.user_id or request.user.is_staff: notice.delete() messages.success(request, f"Nachricht gelöscht") else: messages.warning(request, f"Keine Berechtigung") except: messages.warning(request, f"Nachricht nicht gefunden") return redirect('index') def index(request): notices = Notice.objects.all() notices = notices.filter(pub_start__lte=timezone.now()) notices = notices.filter(pub_end__gte=timezone.now()) context = {'notices': notices} return render(request, 'polls/index.html', context)