34👍
✅
To use decorators in urls.py you need use real functions instead of their names:
from django.contrib.auth.decorators import login_required
import django.views.generic.date_based as views
urlpatterns = patterns('',
(r'^$', login_required(views.archive_index), link_info_dict,
'coltrane_link_archive_index'),
...
7👍
In Django 1.11+, at least, you can do it directly as you want. For example:
# urls.py
from django.contrib.auth.decorators import login_required
urlpatterns = [
# Home path
path('', login_required(TemplateView.as_view(template_name='core/home.html')), name='home'),
# Another paths
# ...
]
In this case, each time you try to enter the homepage, you must be logged in, otherwise you will go to the login screen and then return to your homepage.
- [Django]-Django internationalization language codes
- [Django]-Query for top x elements in Django
- [Django]-DRF testing: instead of JSON an OrderedDict is returned
1👍
- [Django]-Django – Static file not found
- [Django]-Parsing a Datetime String into a Django DateTimeField
- [Django]-Django Rest frameworks: request.Post vs request.data?
0👍
Those docs are for generic views, which work slightly differently than custom views. Normally login_required
is used to decorate a view; if you want to use it within a urlconf then you’ll need to write a lambda to wrap the view.
- [Django]-How to make FileField in django optional?
- [Django]-How to make Django's DateTimeField optional?
- [Django]-Example of Django Class-Based DeleteView
0👍
For Django v4.1.4,
In addition to @catavaran’s answer, when you are using a Custom Login URL instead of django’s default login, then you need to give the custom url to the login_url parameter.
urls.py
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('', login_required(TemplateView.as_view(template_name='app_name/template_name.html'),login_url='/custom_login_url/'), name='path-name'),
]
- [Django]-Delete Duplicate Rows in Django DB
- [Django]-Adding css class to field on validation error in django
- [Django]-Simple search in Django
Source:stackexchange.com