Django - How to treat Exception returned when I try to access a view protected by Developer @login_required?

Asked

Viewed 495 times

3

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

The project in Github

py views.

# -*- 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,                                 
                }
            )

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

1 answer

2


Set the LOGIN_URL property in Django settings.

To set a view as the error page:

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

And the 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:

  • I have already defined these two properties in Settings.py but Exception persists, according to the documentation, by default, when trying to access a view without being logged in, it should redirect to login screen (LOGIN_URL)but when I do it redirects me to the Exception Noreversematch error screen.

  • See the new version.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.