Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the The login_required decorator in my URL?

I want to check that the user is authorized for certain URLs. I'm using generic views.

The docs here say the login_required can be passed as an optional arguments but I'm not sure. Something like this maybe: (r'^$', 'archive_index', link_info_dict, 'coltrane_link_archive_index', login_required=True,),

I have this and I would like to be able to use the login_required decorator within the URL. Is it possible? How can I do it?

from django.conf.urls.defaults import *

from coltrane.models import Link

link_info_dict = {
    'queryset': Link.live.all(),
    'date_field': 'pub_date',
}

urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index', link_info_dict, 'coltrane_link_archive_index'),

    (r'^(?P<year>\d{4})/$', 'archive_year', link_info_dict, 'coltrane_link_archive_year'),

    (r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', link_info_dict, 'coltrane_link_archive_month'),

    (r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', link_info_dict, 'coltrane_link_archive_day'),

    (r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', link_info_dict, 'coltrane_link_detail'),

)


For example how would I protect this page here(there's no view to add the login_Required decorator to)?

(r'^$', 'django.views.generic.simple.direct_to_template', {
        'template': 'home.html'
    }, ),
like image 577
darren Avatar asked Apr 19 '11 21:04

darren


3 Answers

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'),
    ...
like image 187
catavaran Avatar answered Nov 19 '22 21:11

catavaran


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.

like image 32
cjadeveloper Avatar answered Nov 19 '22 19:11

cjadeveloper


you can use decorate_url

http://github.com/vorujack/decorate_url

pip install decorate_url
like image 31
vorujack Avatar answered Nov 19 '22 21:11

vorujack