1
0
clubhaus-schornbach/clubhaus/homepage/views.py

67 lines
2.5 KiB
Python

import django.utils.timezone
from django.core.cache import cache
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import Tobacco, ClubhausEvent, EventDate, EventDateVotes
import clubhaus.settings as django_settings
def index(request: HttpRequest) -> django.http.HttpResponse:
return render(request, 'homepage/index.html', {})
def tobacco(request: HttpRequest) -> django.http.HttpResponse:
context = {'tobaccos': Tobacco.objects.all().order_by('-in_stock')}
return render(request, 'homepage/tobacco.html', context)
def events(request: HttpRequest) -> django.http.HttpResponse:
next_events = ClubhausEvent.objects.filter(active=True).order_by('-id')
if len(next_events) == 1:
next_event = next_events[0]
dates = EventDate.objects.filter(event=next_event).order_by("date")
votes = EventDateVotes.objects.filter(date__event=next_event)
voter_names = sorted(set(map(lambda v: v.name, votes)))
vote_map = {}
for voter_name in voter_names:
vote_map[voter_name] = {date.date.isoformat(): False for date in dates}
for vote in votes:
v_name = vote.name
v_date = vote.date.date.isoformat()
if v_name in vote_map and v_date in vote_map[v_name]:
vote_map[v_name][v_date] = True
return render(request, 'homepage/events.html', {'next_event': next_event, "dates": dates, 'votes': vote_map})
else:
return HttpResponseRedirect(reverse("index"))
def voting(request: HttpRequest) -> django.http.HttpResponse:
request.session.clear_expired()
# Proxy use is forbidden
if request.META.get("X-Forwarded-For"):
return HttpResponseForbidden()
ip = request.META.get("REMOTE_ADDR")
cache_key = f"voting_block_{ip}"
rate_cache: django.core.cache.BaseCache = cache
if ip not in rate_cache:
rate_cache.add(cache_key, 0, django_settings.IP_RATE_LIMIT_TIME)
rate_cache.incr(cache_key)
if request.method == "POST" and rate_cache.get(cache_key) < 3:
if name := request.POST["name"]:
request.session["name"] = name
for date in EventDate.objects.filter(event__active=True).order_by("date"):
if date.date.isoformat() in request.POST:
EventDateVotes.objects.update_or_create(name=name, date=date)
else:
EventDateVotes.objects.filter(name=name, date=date).delete()
return HttpResponseRedirect(reverse("events"))