kpsul/bds/views.py
2020-07-20 11:11:53 +02:00

62 lines
2.1 KiB
Python

from django.contrib import messages
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView
from bds.autocomplete import bds_search
from bds.forms import ProfileForm, UserForm
from bds.mixins import StaffRequiredMixin
from shared.views import AutocompleteView
User = get_user_model()
class BDSAutocompleteView(StaffRequiredMixin, AutocompleteView):
template_name = "bds/search_results.html"
search_composer = bds_search
class Home(StaffRequiredMixin, TemplateView):
template_name = "bds/home.html"
class UserUpdateView(StaffRequiredMixin, TemplateView):
template_name = "bds/user_update.html"
def get_user(self):
return get_object_or_404(User, pk=self.kwargs["pk"])
def get_user_form(self, data=None):
return UserForm(prefix="u", instance=self.user, data=data)
def get_profile_form(self, data=None):
profile = getattr(self.user, "bds", None)
return ProfileForm(prefix="p", instance=profile, data=data)
def get_context_data(self, user_form=None, profile_form=None, **kwargs):
return {
"user_form": user_form or self.get_user_form(),
"profile_form": profile_form or self.get_profile_form(),
}
def get(self, *args, **kwargs):
self.user = self.get_user()
return super().get(*args, **kwargs)
def post(self, request, *args, **kwargs):
self.user = self.get_user()
user_form = self.get_user_form(data=request.POST)
profile_form = self.get_profile_form(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
self.user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = self.user
profile.save()
messages.success(self.request, _("Profil mis à jour avec succès"))
else:
messages.error(self.request, _("Veuillez corriger les erreurs ci-dessous"))
return self.render_to_response(self.get_context_data(user_form, profile_form))