Add AuthenticatedHttpRequest type for helping with LoginRequiredMixin views

This commit is contained in:
Bruno Alla 2024-07-28 10:18:38 +02:00
parent 6355464230
commit bb8a1b6637
No known key found for this signature in database

View File

@ -1,6 +1,7 @@
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import QuerySet from django.db.models import QuerySet
from django.http import HttpRequest
from django.urls import reverse from django.urls import reverse
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView from django.views.generic import DetailView
@ -10,6 +11,11 @@ from django.views.generic import UpdateView
from {{ cookiecutter.project_slug }}.users.models import User from {{ cookiecutter.project_slug }}.users.models import User
class AuthenticatedHttpRequest(HttpRequest):
"""For mypy to know that the user is authenticated."""
user: User
class UserDetailView(LoginRequiredMixin, DetailView): class UserDetailView(LoginRequiredMixin, DetailView):
model = User model = User
{%- if cookiecutter.username_type == "email" %} {%- if cookiecutter.username_type == "email" %}
@ -19,6 +25,7 @@ class UserDetailView(LoginRequiredMixin, DetailView):
slug_field = "username" slug_field = "username"
slug_url_kwarg = "username" slug_url_kwarg = "username"
{%- endif %} {%- endif %}
request: AuthenticatedHttpRequest
user_detail_view = UserDetailView.as_view() user_detail_view = UserDetailView.as_view()
@ -28,15 +35,12 @@ class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = User model = User
fields = ["name"] fields = ["name"]
success_message = _("Information successfully updated") success_message = _("Information successfully updated")
request: AuthenticatedHttpRequest
def get_success_url(self) -> str: def get_success_url(self) -> str:
# for mypy to know that the user is authenticated
assert self.request.user.is_authenticated
return self.request.user.get_absolute_url() return self.request.user.get_absolute_url()
def get_object(self, queryset: QuerySet | None=None) -> User: def get_object(self, queryset: QuerySet | None=None) -> User:
# for mypy to know that the user is authenticated
assert self.request.user.is_authenticated
return self.request.user return self.request.user
@ -45,6 +49,7 @@ user_update_view = UserUpdateView.as_view()
class UserRedirectView(LoginRequiredMixin, RedirectView): class UserRedirectView(LoginRequiredMixin, RedirectView):
permanent = False permanent = False
request: AuthenticatedHttpRequest
def get_redirect_url(self) -> str: def get_redirect_url(self) -> str:
{%- if cookiecutter.username_type == "email" %} {%- if cookiecutter.username_type == "email" %}