1๐
If you really want to modify the default views, one option would be to subclass them and use them in your urls.
In your views (using UserPassesTestMixin
class):
from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib.auth.views import PasswordResetView
class MyPasswordResetView(UserPassesTestMixin, PasswordResetView):
template_name = 'users/password_reset.html'
# https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.is_anonymous
def test_func(self):
return self.request.user.is_anonymous
In your urls:
from .views import MyPasswordResetView
...
path(
'password_reset/',
MyPasswordResetView.as_view(),
name="password_reset"),
...
You should learn to read the linked docs to find your answers. It says here:
[โฆ] you can set any of the parameters of
AccessMixin
to customize the handling of unauthorized users [โฆ]
And under AccessMixin
you can find the attributes and methods to redirect unauthorized users.
3๐
Multiple ways to do this; However, I think that the quickest solution would be to write a decorator:
def login_forbidden(function=None):
actual_decorator = user_passes_test(
lambda u: u.is_anonymous,
)
if function:
return actual_decorator(function)
return actual_decorator
and use it to decorate the password reset views where you want to restrict access only to unauthenticated users:
path('password_reset/', login_forbidden(auth_views.PasswordResetView.as_view(template_name='users/password_reset.html')), name="password_reset")
Alternatively, you can override the actual views.
- [Django]-In Django, how to rename user model?
- [Django]-Django Admin Inlines with many fields, possible to have inline add button create popup?
2๐
You can use {% if user.is_authenticated %}
or {% if user.is_anonymous %}
and put that directly in your template no need to modify the view:
{% if user.is_anonymous %}
# user is not logged in
...
{% else %}
# user is logged in
...
{% endif %}
- [Django]-How to create a custom 404 page for my Django/Apache?
- [Django]-POST API response blocked by CORS policy โ React and Django Rest Framwork
- [Django]-Caught TypeError while rendering: 'BoundField' object is not iterable
- [Django]-Django filter queryset by attribute subclass