避免“ DoesNotExist位于/​​”

时间:2019-01-26 12:33:56

标签: python django web

我做了一个登录视图,该视图运行良好。问题是我想避免使用Django的默认模板消息:

DoesNotExist at /
 Usuario matching query does not exist.
  Request Method:   POST
  Request URL:  http://localhost:8000/
  Django Version:   2.1.5
  Exception Type:   DoesNotExist
  Exception Value: Usuario matching query does not exist.

我尝试发送自己的登录错误消息,而不是这样,我的代码如下:

def login(request):
    if request.method == "POST":
        print('Form is post.')
        form = LoginForm(request.POST)
        if form.is_valid():
            print('Form is valid.')
            loginUser = form.cleaned_data.get('nombreUsuario')
            loginPass = form.cleaned_data.get('password')
            loginEmp = form.cleaned_data.get('nombreEmpresa')
            encontroUsuario = Usuario.objects.get(nombre=loginUser, password=loginPass)
            encontroEmpresa = Empresa.objects.get(nombre=loginEmp)
            if encontroUsuario and encontroEmpresa:
                return HttpResponse('Logueado con éxito.')
            if encontroUsuario.DoesNotExist or encontroEmpresa.DoesNotExist:
                return render(request, "loginError.html", {"form": form})
    else:
        form = LoginForm
        return render(request, "login.html", {"form": form})

1 个答案:

答案 0 :(得分:0)

您可以使用try-except捕获异常:

from django.core.exceptions import ObjectDoesNotExist

def login(request):
    if request.method == "POST":
        print('Form is post.')
        form = LoginForm(request.POST)
        if form.is_valid():
            print('Form is valid.')
            loginUser = form.cleaned_data.get('nombreUsuario')
            loginPass = form.cleaned_data.get('password')
            loginEmp = form.cleaned_data.get('nombreEmpresa')
            try:
                encontroUsuario = Usuario.objects.get(nombre=loginUser, password=loginPass)
                encontroEmpresa = Empresa.objects.get(nombre=loginEmp)
            except ObjectDoesNotExist:
                return render(request, "loginError.html", {"form": form})
            return HttpResponse('Logueado con exito.')
    else:
        form = LoginForm
        return render(request, "login.html", {"form": form})

最好用try分别except-objects.get(..)两个except ModelDoesNotExist

但是请注意,您应该存储原始密码,而应该散列这些密码。实际上,Django的用户模型具有用于此目的的工具。在documentation on authentication [Django-doc]上了解更多。