Django: Login_required(redirect to custom login_url) not working

628 Views Asked by At

views.py file

@login_required(login_url='frontpage')
def dash(request):
    events = Event.objects.all()
    if request.method == 'POST':
        form = createEventForm(request.POST)
        args = {'form':form , 'events':events}
        if form.is_valid():
            form.save(request.POST)
        return render(request, 'dashboard/index.html',args)
    else:
        form = createEventForm()
        args = {'form':form , 'events':events}
        return render(request, 'dashboard/index.html',args)

urls.py file

urlpatterns = [
    url('admin/', admin.site.urls),
    url(r'^$', frontviews.login),
    path('', frontviews.login, name = "login"),
    url(r'frontpage^/$', frontviews.login, name = "frontpage"),
    url(r'^dashboard/$', dashviews.dash, name = "dashboard"),#require login to fix
    url(r'^$', dashviews.logout, name = "logout"),
    url(r'^forum/$', forumviews.forumpage, name = 'forum'),
    url(r'^events/$', dashviews.EventPage, name = 'events'),
]

I want the user to be required to login from the frontpage(of website), i.e. i want to redirect user to frontpage if he tries to use url[website.com/dashboard] to directly enter dashboard. Any help will be appreciated...

1

There are 1 best solutions below

0
Riyas Ac On BEST ANSWER

Only change url of the frontpage. Your wrong url

url(r'frontpage^/$', frontviews.login, name = "frontpage"),

The below url is correct.

url(r'^frontpage/$', frontviews.login, name = "frontpage"),

The ^ matches the beginning of the string. so it doesn’t use other position of the url.