Mike Slinn
Mike Slinn

Experimenting With Django User Authentication

Published 2021-03-19.

This article is categorized under Django, Visual Studio Code.

I skimmed the documentation for Django how to require user authentication for specific views. It seemed simple enough, all that is supposedly necessary to restrict a view to being visible to logged-in users is to preface the view method that needs logged in users with @login_required, like this:

from django.contrib.auth.decorators import login_required
@login_required def index(request) -> str: return render(request, 'mypage.html')

When I did that to my version of Frobshop nothing changed. There was no login challenge and no error message. I did not know if it was possible to create a log detailed enough to help me figure out what was wrong.

Looking For @login_required

In the django-oscar repository, git grep @login_required returns nothing. However, git grep login_required (without the @ symbol) returns 46 instances, including imports and usages. Here are two of the lines returned from src/oscar/apps/customer/apps.py:

from django.contrib.auth.decorators import login_required
path('', login_required(self.summary_view.as_view()), name='summary'),

I went back to my version of Frobshop and modified it to match what I saw in the django-oscar source code; I specified login_required in urls.py, instead of using @login_required in views.py.

It worked! 😁

Maybe I’ll ask why it worked in the django-oscar Slack group some day. So much to do...