nuitdelinfo_2021/people/views.py

67 lines
2 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 06:20:07 +01:00
from django.core import serializers
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-02 23:46:42 +01:00
from django.urls import reverse
2021-12-02 21:57:32 +01:00
2021-12-02 23:46:42 +01:00
from people.forms import SubmitPeople
2021-12-02 21:57:32 +01:00
from people.models import People
2021-12-02 23:46:42 +01:00
def get_people(people_id: int) -> People:
2021-12-02 21:57:32 +01:00
try:
2021-12-02 23:46:42 +01:00
return People.objects.get(pk=people_id)
2021-12-02 21:57:32 +01:00
except People.DoesNotExist:
raise Http404("People does not exist")
2021-12-02 23:46:42 +01:00
2021-12-03 02:37:28 +01:00
def index(request):
2021-12-03 06:20:07 +01:00
return render(request, "people/peoples.html", {
"peoples": People.objects.all()
2021-12-03 02:37:28 +01:00
})
def details(request, people_id: int):
2021-12-02 23:46:42 +01:00
return render(request, "people/people.html", {
"people": get_people(people_id)
2021-12-02 21:57:32 +01:00
})
2021-12-02 23:46:42 +01:00
2021-12-03 04:52:09 +01:00
2021-12-03 01:11:23 +01:00
@login_required
2021-12-02 23:46:42 +01:00
def submit(request):
if request.method == "POST":
form = SubmitPeople(request.POST)
if form.is_valid():
people = form.save()
2021-12-03 04:52:09 +01:00
return HttpResponseRedirect(reverse(details, args=[people.pk]))
2021-12-02 23:46:42 +01:00
else:
form = SubmitPeople()
return render(request, "people/submit.html", {"form": form})
2021-12-03 01:11:23 +01:00
@login_required
2021-12-02 23:46:42 +01:00
def edit(request, people_id: int):
edited_people = get_people(people_id)
if not edited_people.validated:
return HttpResponseBadRequest("This entry is not validated, you can't edit it")
if request.method == "POST":
form = SubmitPeople(request.POST)
if form.is_valid():
people = form.save()
people.pending_edit_of = edited_people
people.save()
2021-12-03 04:52:09 +01:00
return HttpResponseRedirect(reverse(details, args=[people.pk]))
2021-12-02 23:46:42 +01:00
else:
edited_people.pk = None
form = SubmitPeople(instance=edited_people)
return render(request, "people/edit.html", {"form": form, "edit_id": people_id})
2021-12-03 04:34:10 +01:00
def ajax_search(request, text: str):
2021-12-03 06:20:07 +01:00
return JsonResponse(serializers.serialize("json", People.objects.filter(Q(first_name__icontains=text) | Q(first_name__icontains=text))), safe=False)