I've made a class-based view (DetailView) of app user's profile and for some reason anyone who visits the view is automatically considered authenticated even without entering any credentials. This happens without adding any extra logic in neither view nor template, just basic DetailView. The code is below:
views.py
from django.views.generic import DetailView
from django.contrib.auth.models import User
class ProfileDetail(DetailView):
model = User
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
urls.py
from django.urls import path
from .views import ProfileDetail
urlpatterns = [
path('<int:pk>/', ProfileDetail.as_view())
]
template (index.html)
{{ user.is_authenticated }} {# returns True #}
{{ user }} {# returns the user with the corresponding id #}
The question is why does Django do it and is there any way to circumvent it except of using function-based view? I've looked through the docs, but couldn't find an answer.
CodePudding user response:
To implement authentication in Django Class-Based Views, I've used LoginRequiredMixin, as it's explained here: https://docs.djangoproject.com/es/4.0/topics/auth/default/
Code (from Django site):
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
Another way is to pass the view that we want to authenticate to the login_required function, in the mapping of urls.py:
from django.contrib.auth.decorators import login_required
path('<int:pk>/', login_required(ProfileDetail.as_view())) #not tested
CodePudding user response:
The simplest way to make any page login_required
in class based views is to use method_decorator
django-doc
In your ProfileDetail
you can implement in the following way:
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator method_decorator(login_required(login_url="/any_login_route/"),name='dispatch') class ProfileDetail(DetailView): ... ...
It will make the page login_required,and set login_url
so that it can redirect to login page if user is not authenticated, for more information you can see docs by clicking on above method.