使用Django验证用户

问题描述 投票:0回答:2

我有登录html页面和索引html页面但是当我写下用户名和密码时,页面只刷新而不做任何事情。我使用Django 2.x和Python 3.4

登录html中的代码:

      <form class="form-signin" action='{% url 'myapp:index' %}' method="post">
    {% csrf_token %}

    <img class="mb-4" src='{% static 'app/img/logo.png' %}' alt="" width="300" height="100">

    <h1 class="h3 mb-3 font-weight-normal">mysite</h1>
    <br>
    <div class="group">
        <input type="username" id="inputUser" name="username" class="form-control" placeholder="Username" required autofocus alt="" width="300" height="100">
    </div>

    <div class="group">
        <input type="password" id="inputPassword" name="password" class="form-control" placeholder="Password" required alt="" width="300" height="100">
    </div>

    <div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Accedi</button>
    </div>

  </form>

在这里我的观点:

def index(request):
    username = request.post["username"]
    password = request.post["password"]
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        return render(request, "myapp/index.html")

我做错了什么?谢谢

编辑:

我的error.log

AH00558:httpd.exe:无法使用fe80 :: 1c06:8ac5:1b1e:aa2f可靠地确定服务器的完全限定域名。全局设置'ServerName'指令以禁止显示此消息[Thu Aug 02 12:35:17.911829 2018] [mpm_winnt:notice] [pid 4196:tid 452] AH00455:Apache / 2.4.34(Win64)mod_wsgi / 4.6.4 Python /3.6配置 - 恢复正常操作[Thu Aug 02 12:35:17.912829 2018] [mpm_winnt:notice] [pid 4196:tid 452] AH00456:Apache Lounge VC15 Server内置:2018年7月11日13:09:01 [8月8日] 02 12:35:17.912829 2018] [核心:通知] [pid 4196:tid 452] AH00094:命令行:'c:\ Apache \ bin \ httpd.exe -d C:/ Apache'[Thu Aug 02 12:35 :17.913829 2018] [mpm_winnt:notice] [pid 4196:tid 452] AH00418:父:创建子进程2112 AH00558:httpd.exe:无法可靠地确定服务器的完全限定域名,使用fe80 :: 1c06:8ac5:1b1e :aa2f。全局设置'ServerName'指令以禁止显示此消息AH00558:httpd.exe:无法使用fe80 :: 1c06:8ac5:1b1e:aa2f可靠地确定服务器的完全限定域名。全局设置'ServerName'指令以禁止此消息[Thu Aug 02 12:35:18.335853 2018] [mpm_winnt:notice] [pid 2112:tid 472] AH00354:Child:启动64个工作线程。

我的access.log:

myip - - [02 / Aug / 2018:12:35:28 +0200]“GET / myapp / HTTP / 1.1”200 2633 myip - - [02 / Aug / 2018:12:35:48 +0200]“POST / myapp / HTTP / 1.1“200 2633

EDIT2:我将url.py从路径更改为url并解决了问题...现在页面加载正确,感谢大家

django python-3.x
2个回答
0
投票
user = authenticate(request, username=username, password=password)

无需将请求作为参数传递

user = authenticate(username=username,password=password)

它可以解决您的错误。

另一种方式 - 您也可以参考本教程:https://simpleisbetterthancomplex.com/tutorial/2016/06/27/how-to-use-djangos-built-in-login-system.html


0
投票

你可以尝试这个: -

from django.contrib.auth.forms import AuthenticationForm

def index(request):
form = AuthenticationForm(None, request.POST)
if form.is_valid():
    login(request, form.get_user())
    return render(request, "index.html", {'message':"successfully login"})
© www.soinside.com 2019 - 2024. All rights reserved.