nuitdelinfo_2021/rescue/views.py

62 lines
1.9 KiB
Python
Raw Normal View History

2021-12-03 01:11:23 +01:00
from django.contrib.auth.decorators import login_required
2021-12-03 04:34:10 +01:00
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect, HttpResponseBadRequest, JsonResponse
2021-12-02 21:57:32 +01:00
from django.shortcuts import render
2021-12-03 00:23:06 +01:00
from django.urls import reverse
2021-12-02 21:57:32 +01:00
2021-12-03 00:23:06 +01:00
from rescue.forms import SubmitRescue
from rescue.models import Rescue
2021-12-02 21:57:32 +01:00
2021-12-03 00:23:06 +01:00
def get_rescue(rescue_id: int) -> Rescue:
try:
return Rescue.objects.get(pk=rescue_id)
except Rescue.DoesNotExist:
raise Http404("Rescue does not exist")
2021-12-03 02:37:28 +01:00
def index(request):
return render(request, "article/articles.html", {"rescues": Rescue.objects.all()})
def details(request, rescue_id: int):
2021-12-03 00:23:06 +01:00
return render(request, "article/article.html", {"rescue": get_rescue(rescue_id)})
2021-12-03 01:11:23 +01:00
@login_required
2021-12-03 00:23:06 +01:00
def submit(request):
if request.method == "POST":
form = SubmitRescue(request.POST)
if form.is_valid():
rescue = form.save()
return HttpResponseRedirect(reverse(index, args=[rescue.pk]))
else:
form = SubmitRescue()
return render(request, "article/submit.html", {"form": form})
2021-12-03 01:11:23 +01:00
@login_required
2021-12-03 00:23:06 +01:00
def edit(request, rescue_id: int):
edited_rescue = get_rescue(rescue_id)
if not edited_rescue.validated:
return HttpResponseBadRequest("This entry is not validated, you can't edit it")
if request.method == "POST":
form = SubmitRescue(request.POST)
if form.is_valid():
rescue = form.save()
rescue.pending_edit_of = edited_rescue
rescue.save()
return HttpResponseRedirect(reverse(index, args=[rescue.pk]))
else:
edited_rescue.pk = None
form = SubmitRescue(instance=edited_rescue)
return render(request, "article/edit.html", {"form": form, "edit_id": edited_rescue})
2021-12-03 04:34:10 +01:00
def ajax_search(request, text: str):
return JsonResponse(Rescue.objects.filter(Q(name__icontains=text) | Q(date__icontains=text) | Q(resume__icontains=text)))