gestiojeux/loans/views.py
Sylvain Gay 474083dd38 Add minimal loans system
Functional loans system for users.
No manager interface yet.

See:
- app "loans"
- a few new views/templates in app "inventory"
2024-05-02 11:13:34 +02:00

70 lines
2.4 KiB
Python

from django.views.generic import DetailView, FormView, RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib import messages
from django.shortcuts import redirect
from inventory.models import Game
from .models import AbstractLoan
from .forms import BorrowForm
class ReturnView(SingleObjectMixin, RedirectView):
# Inherited classes should contain:
# model = LoanModel
# pattern_name =
redirect_slug_field = "slug"
permanent = False
def get_redirect_url(self, *args, **kwargs):
loan = self.get_object()
loan.return_object()
kwargs[self.redirect_slug_field] = getattr(loan.lent_object,
loan.lent_object_slug_field)
messages.success(self.request, "Rendu effectué.")
return super().get_redirect_url(*args, **kwargs)
class BorrowView(SingleObjectMixin, FormView):
# Inherited classes should contain:
# model = LentObjectModel
# loan_model = LoanModel
# template_name = "path/to/template.html"
form_class = BorrowForm # Update this for a more complex form
def get_initial(self):
initial = super().get_initial()
if "loan_mail" in self.request.session:
initial["mail"] = self.request.session["loan_mail"]
return initial
def get_context_data(self, **kwargs):
self.object = self.get_object()
return super().get_context_data(**kwargs)
def form_valid(self, form):
obj = self.get_object()
ongoing = self.loan_model.ongoing_loans(obj)
if ongoing.exists():
ongoing.get().return_object()
loan = self.loan_model(lent_object=obj, mail=form.cleaned_data["mail"])
loan.save()
self.request.session["loan_mail"] = loan.mail
messages.success(self.request, "Votre emprunt est enregistré.")
return redirect(self.success_pattern_name,
getattr(obj, loan.lent_object_slug_field))
class DetailLoanView(DetailView):
# Inherited classes should contain:
# model = LentObjectModel
# loan_model = LoanModel
# template_name = "path/to/template.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
loans = self.loan_model.ongoing_loans(self.get_object())
is_borrowed = loans.exists()
context["is_borrowed"] = is_borrowed
if is_borrowed:
context["loan"] = loans.get()
return context