pflaenz.li/pflaenzli/pflaenzli/views.py
Jannis Portmann b9fa20e4d6
All checks were successful
continuous-integration/drone/push Build is passing
Overhaul PLZ
2023-10-15 00:29:21 +02:00

251 lines
8.3 KiB
Python

from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.utils.translation import activate, get_language
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_POST
from .forms import CreateOfferForm, FilterForm, RegistrationForm, WishForm
from .mail import send_offer_email
from .models import Offer, PflaenzliUser, Wish, Plz
from .upload import generate_unique_filename
from .utils.compress_image import compress_image
from .utils.distance import calculate_distance, filter_by_distance
def list_offers(request, filters=None):
offers = Offer.objects.all()
if request.method == "POST":
form = FilterForm(request.POST, request.FILES)
if form.is_valid():
offers = filter_offers(offers, form)
else:
form = FilterForm()
return render(request, "offer/search.html", {"offers": offers, "form": form})
@login_required
def create_offer(request):
if request.method == "POST":
form = CreateOfferForm(request.POST, request.FILES)
if form.is_valid():
offer = form.save(commit=False)
offer.image.name = generate_unique_filename(form.cleaned_data['image'].name)
offer.image = compress_image(offer.image, offer.image.name)
offer.user = request.user
offer.title = offer.title.title()
offer.save()
messages.success(request, _("Offer uploaded successfully!"))
return redirect("offer_detail", offer.id)
else:
form = CreateOfferForm()
return render(request, "basic_form.html", {"form": form, "button_label": _("Create"), "title": _("Create offer"), "umami_event": "Offer create"})
def offer_detail(request, offer_id):
offer = get_object_or_404(Offer, id=offer_id)
wishes = Wish.objects.filter(user=offer.user)
if request.user.is_authenticated:
if offer.zipcode and request.user.zipcode:
if offer.zipcode == request.user.zipcode:
dist = 0
else:
dist = calculate_distance(Plz.objects.get(plz=offer.zipcode), Plz.objects.get(plz=request.user.zipcode))
else:
dist = None
else:
dist = None
return render(request, "offer/detail.html", {"offer": offer, "wishes": wishes, "dist": dist})
@login_required
def offer_delete(request, offer_id):
offer = get_object_or_404(Offer, id=offer_id)
if offer.user != request.user:
return HttpResponseForbidden()
offer.delete()
messages.success(request, _("Offer deleted successfully!"))
return redirect("list_offers")
@login_required
def offer_edit(request, offer_id):
offer = get_object_or_404(Offer, id=offer_id)
if offer.user != request.user:
return HttpResponseForbidden()
if request.method == "POST":
form = CreateOfferForm(request.POST, request.FILES, instance=offer)
if form.is_valid():
offer = form.save(commit=False)
if 'image' in request.FILES:
offer.image.name = generate_unique_filename(form.cleaned_data['image'].name)
offer.image = compress_image(offer.image, offer.image.name)
else:
offer.image = offer.image
offer.user = request.user
offer.save()
messages.success(request, _("Offer updated successfully!"))
return redirect("offer_detail", offer.id)
else:
form = CreateOfferForm(instance=offer)
return render(request, "basic_form.html", {"form": form, "button_label": _("Save"), "title": _("Edit Offer")})
@login_required
def wishlist(request, user_id):
wishes = Wish.objects.filter(user=user_id)
if user_id == request.user.id:
title = _("Your wishlist")
if request.method == "POST":
form = WishForm(request.POST)
if form.is_valid():
wish = form.save(commit=False)
wish.user = request.user
wish.save()
messages.success(request, _("Wish added successfully!"))
form = WishForm()
else:
form = None
user = get_object_or_404(PflaenzliUser, id=user_id)
title = f"{user.username}'s {_('wishlist')}"
return render(request, "user/wish.html", {"title": title, "form": form, "wishes": wishes, "own": user_id == request.user.id})
@login_required
def user_edit(request):
if request.method == "POST":
form = RegistrationForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.success(request, _("Account details updated successfully!"))
return redirect("user_profile")
else:
form = RegistrationForm(instance=request.user)
return render(request, "basic_form.html", {"form": form, "button_label": _("Save"), "title": _("Edit Account Details")})
@csrf_protect
@require_POST
@login_required
def delete_wish(request, wish_id):
wish = get_object_or_404(Wish, id=wish_id)
if wish.user != request.user:
messages.error(request, "You don't have permission to delete this wish!")
return redirect("wishlist", request.user.id)
wish.delete()
return redirect("wishlist", request.user.id)
@login_required
def offer_trade(request):
offer_id = int(request.POST['offer'])
offer = get_object_or_404(Offer, id=offer_id)
sender = request.user
recipient = offer.user
if sender != recipient:
send_offer_email(request, offer, sender, recipient)
messages.success(request, f"{recipient.username} {_('was successfully notified')}!")
else:
messages.error(request, _("You can't trade with yourself!"))
return redirect("offer_detail", offer_id)
def user_detail(request, user_id):
user = get_object_or_404(PflaenzliUser, id=user_id)
offers = Offer.objects.filter(user=user_id)
wishes = Wish.objects.filter(user=user_id)
return render(request, "user/public.html", {"user": user, "offers": offers, "wishes": wishes})
def register_user(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
user.language_code = get_language()
login(request, user)
return redirect("index")
else:
form = RegistrationForm()
return render(request, "basic_form.html", {"form": form, "button_label": _("Register"), "title": _("Registeration"), "umami_event": "User registration", "form_note": mark_safe(_('Please note the <a href="/imprint">privacy policy</a>'))})
def save_language(request):
referer_url = request.META.get('HTTP_REFERER')
response = redirect(referer_url)
if request.method == 'POST':
if language_code := request.POST.get('language'):
if request.user.is_authenticated:
user = request.user
user.language_code = language_code
user.save()
activate(language_code)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language_code)
return response
@login_required
def load_language(request):
response = redirect('user_profile')
language_code = request.user.language_code
activate(language_code)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language_code)
return response
def error_404(request, exception):
return render(request, '404.html')
def error_403(request, exception):
return render(request, '403.html')
def error_500(request):
return render(request, '500.html')
def filter_offers(offers, form):
if category := form.cleaned_data['category']:
if category != 'ALL':
offers = offers.filter(category=category)
if text := form.cleaned_data['text']:
offers = offers.filter(title__icontains=text)
if zipcode := form.cleaned_data['zipcode']:
if form.cleaned_data['distance']:
offers = filter_by_distance(offers, zipcode, form.cleaned_data['distance'])
else:
offers = offers.filter(zipcode=int(zipcode))
return offers