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.
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):
Another way is to pass the view that we want to authenticate to the login_required function, in the mapping of urls.py: