参考:https://www.cnblogs.com/liwenzhou/p/9030211.html

一 auth使用django默认的user表

1 auth常用方法

  1. authenticate() 
  2. login()
  3. create_user()
  4. create_superuser()
  5. logout()
  6. check_password()
  7. set_password()

2 利用auth来实现登录和注册功能

 登录例子:

在登录之前,在settings.py里面必须先设置

LOGIN_URL = '/login/'    # 这里配置成你项目登录页面的路由

否则登录的时候默认会跳到http://127.0.0.1:8000/accounts/login/

from django.contrib import auth # 必须先导入auth


# 登录
def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    else:
        next_url = request.GET.get("next")
        print(next_url)
        username = request.POST.get("username")
        pwd = request.POST.get("password")
        user_obj = auth.authenticate(request, username=username, password=pwd)
        if user_obj:
            auth.login(request, user_obj)  # # 给该次请求设置了session数据,并在响应中回写cookie
            if next_url:
                return redirect(next_url)
            else:
                return redirect("/book_list/")
        else:
            return render(request, "login.html", {"error_msg": "用户名或密码错误"})

html页面

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1>登陆</h1>
 9 <a href="/reg/">注册</a>
10 <form action="" method="post">
11     {% csrf_token %}
12     <p>
13         <input type="text" name="username">
14     </p>
15     <p>
16         <input type="password" name="password">
17     </p>
18     <p>
19         <input type="submit">
20         <span>{{ error_msg }}</span>
21     </p>
22 </form>
23 
24 </body>
25 </html>
View Code

相关文章:

  • 2022-12-23
  • 2021-12-15
  • 2021-09-03
  • 2021-12-28
  • 2022-02-04
  • 2021-05-30
  • 2022-12-23
猜你喜欢
  • 2021-09-22
  • 2021-11-12
  • 2022-12-23
相关资源
相似解决方案