Django - How to handle Exception returned when trying to access a view protected by the @login_required decorator?

3

When the Exception occurs I want to make a redirect to an access denied template!

The project at GitHub

views.py

# -*- coding: utf-8 -*-


## --------------------------- IMPORTS

from django.shortcuts import render, render_to_response
from django.http.response import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout 
from django.contrib.auth.decorators import login_required


from library.models import *
from library.forms import *


## ------------------------------------------- START VIEWS


def index(request):

    next = request.REQUEST.get('next', 'cadBiblioteca')
    username = request.REQUEST.get('username')
    password = request.REQUEST.get('password')
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(next)

    return render(request, 'index.html',
                {
                    'next':next,
                }
            )


def cadSistema(request):

    novo_usuario = User.objects.all()
    if request.method == "POST":

        username = request.REQUEST.get('username') 
        email = request.REQUEST.get('email') 
        password = request.REQUEST.get('password')

        novo_usuario = User.objects.create_user(username, email, password)
        novo_usuario.save()
        return HttpResponseRedirect(reverse('nIndex'))        
    else:
        pass

    return render(request, 'cadastro_sistema.html',
                {

                }
            )

@login_required
def home(request):
    return render(request, 'home.html')


## --------------------------- START CADASTROS

@login_required
def cadBiblioteca(request):

    biblioteca = Biblioteca.objects.all() #Lista de bibliotecas | query
    if request.method == "POST":
        form = FormBiblioteca(request.POST)
        if form.is_valid(): # Processando o Formulario
            nova_lib = form.save()
            return HttpResponseRedirect(reverse('nCadLib'))
    else:
        form = FormBiblioteca()

    return render(request, 'cadastro_library.html',
                {
                    'form':form,                                 
                }
            )


@login_required
def cadLivro(request):

    livros = Livro.objects.all() 
    if request.method == "POST":
        form = FormLivro(request.POST)
        if form.is_valid(): 
            novo_livro = form.save()
            return HttpResponseRedirect(reverse('nCadLivro'))
    else:
        form = FormLivro()

    return render(request, 'cadastro_livro.html',
                {
                    'form':form,                                 
                }
            )

urls.py:

# -*- coding: utf-8 -*-


## --------------------------- IMPORTS

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static 
from django.conf import settings

from django.contrib import admin
admin.autodiscover()

from library.views import * 


## ------------------------------------------- START URLS


urlpatterns = patterns('',

    #===============================================================================#
    #                                URL's Library                                  #

    url(r'^$', 'library.views.index', name='nIndex'),
    url(r'^home/$', 'library.views.home', name='nHome'),

    url(r'^cadBiblioteca/$', cadBiblioteca, name='nCadLib'),
    url(r'^cadLivro/$', cadLivro, name='nCadLivro'),
    url(r'^cadUsuario/$', cadUsuario, name='nCadUsuario'),
    url(r'^cadFuncionario/$', cadFuncionario, name='nCadFunc'),
    url(r'^emprestimo$', cadEmprestimo, name='nEmprestimo'),

    url(r'^pesqLivro/$', pesqLivro, name='nPesqLivro'),
    url(r'^pesqUsuario/$', pesqUsuario, name='nPesqUsuario'),
    url(r'^pesqFuncionario/$', pesqFuncionario, name='nPesqFunc'),

    url(r'^relatorios/$', relatorios, name='nRelatorios'),

    url(r'^cadSistema/$', cadSistema, name='nCadSistema'),
    url(r'^\w+/logout/$', sairSistema, name='nLogout'),

    #===============================================================================#
)

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


## ------------------------------------------- END URLS
    
asked by anonymous 20.05.2014 / 20:11

1 answer

2

Set the LOGIN_URL property in Django's settings.

To set a view as the error page:

urlpatterns = patterns('',
   (r'^acesso_negado/$', 'meusite.views.acesso_negado')
)

And LOGIN_URL:

LOGIN_URL = '/acesso_negado'

In view:

from django.shortcuts import render_to_response

def acesso_negado(request):
    return render_to_response('templates/acesso_negado.html')

Reference:

20.05.2014 / 20:44