AI智能
改变未来

django用户注销_Django中的用户注册,登录和注销指南

django用户注销

This article will cover how to allow user registration, login, and logout functionality on a site built using the Django Web Framework.

本文将介绍如何在使用Django Web Framework构建的网站上允许用户注册,登录和注销功能。

Before we begin, the virtual environment is called env, the Django project is called mysite, and the app is called main.

在开始之前,虚拟环境称为env ,Django项目称为mysite ,应用程序称为main 。

用户注册 (User registration)

As you may have seen, Django comes with a built-in user registration form. We just need to configure it to our needs (i.e. collect an email address upon registration).

如您所见,Django带有内置的用户注册表格。 我们只需要根据需要对其进行配置(即在注册时收集电子邮件地址)。

创建注册表 (Create the register form)

env > mysite > main > (New File) forms.py

env> mysite> main>(新文件)Forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# Create your forms here.class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True) class Meta:
model = User
fields = (\"username\", \"email\", \"password1\", \"password2\") def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data[\'email\']
if commit:
user.save()
return user

First, customize the register form in a new file called forms.py.

首先,在名为forms.py的新文件中自定义注册表单。

Django comes with a pre-built register form called

UserCreationForm

that connects to the pre-built model User. However, the UserCreationForm only requires a username and password (password1 is the initial password and password2 is the password confirmation).

Django带有一个名为

UserCreationForm

的预构建注册表单,该表单连接到预构建模型User。 但是,UserCreationForm仅需要一个用户名和密码(password1是初始密码,password2是密码确认)。

So call UserCreationForm within a new class called

NewUserForm

and add another field called

email

. Then save the email to the user.

因此,在名为

NewUserForm

的新类中调用

NewUserForm

并添加另一个名为

email

字段。 然后将电子邮件保存给用户。

This same process can be done with any other fields you wish to add to the UserCreationForm.

您希望添加到UserCreationForm的任何其他字段都可以完成相同的过程。

创建一个register.html文件 (Create a register.html file)

env > mysite > main > templates > main > (New File) register.html

env> mysite> main>模板> main>(New File)register.html

{% extends \"main/header.html\" %}{% block content %} {% load crispy_forms_tags %}         <!--Register--> 
<div class=\"container py-5\">
<h1>Register</h1>
<form method=\"POST\">
{% csrf_token %}
{{ register_form|crispy }}
<button class=\"btn btn-primary\" type=\"submit\">Register</button>
</form>
<p class=\"text-center\">If you already have an account, <a href=\"/login\">login</a> instead.</p>
</div>{% endblock %}

Next, create a HTML template were the form will render. We will call this template register.html.

接下来,创建将要呈现表单HTML模板。 我们将此模板称为register.html 。

The template is built using Bootstrap and Django crispy-forms and also uses the Django extends template tag.

该模板是使用Bootstrap和Django crispy-forms构建的,还使用了Django extended template tag 。

向应用添加注册网址 (Add a register URL to the app)

env > mysite > main > urls.py

env> mysite> main> urls.py

from django.urls import path
from . import viewsapp_name = \"main\"
urlpatterns = [
path(\"\", views.homepage, name=\"homepage\"),
...
path(\"register\", views.register_request, name=\"register\")
]

Now add a register path to the app’s URLs so we can refer to it in the views.

现在将注册路径添加到应用程序的URL,以便我们可以在视图中引用它。

向视图添加注册功能 (Add a register function to the views)

env > mysite > main > views.py

env> mysite> main> views.py

from django.shortcuts import  render, redirect
from .forms import NewUserForm
from django.contrib.auth import login
from django.contrib import messages #import messagesdef register_request(request):
if request.method == \"POST\":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, \"Registration successful.\" )
return redirect(\"main:homepage\")
messages.error(request, \"Unsuccessful registration. Invalid information.\")
form = NewUserForm
return render (request=request, template_name=\"main/register.html\", context={\"register_form\":form})

Import

NewUserForm

from forms.py and

login

from

django.contrib.auth

. Then write a new views function called

register_request

.

从Forms.py导入

NewUserForm

并从

django.contrib.auth
login

。 然后编写一个名为

register_request

的新视图函数。

There are two if/else statements within the function. The first checks to see if the form is being posted while the second checks to see if the form is valid. If both are true, then the form information is saved under a user, the user is logged in, and the user is redirected to the homepage showing a success message.

函数内有两个if / else语句。 第一个检查表单是否被过帐,第二个检查表单是否有效。 如果两者都为真,则将表单信息保存在用户下,用户登录后,该用户将重定向到显示成功消息的主页。

Else, if the form is not valid, an error message is shown. But if the request is not a POST in the first place, meaning the first if statement returned false, render the empty form in the register template.

否则,如果表格无效,则会显示错误消息。 但是,如果请求最初不是POST,则意味着第一个if语句返回false,则在寄存器模板中呈现空格式。

Please note that if you wish to add messages to your Django project you must enable the Messages Framework and import messages at the top of views.py.

请注意,如果要将消息添加到Django项目中,则必须启用Messages Framework并在views.py顶部导入消息。

测试注册用户功能 (Test the register user functionality)

With the register function complete, you can now go to the register URL, http://127.0.0.1:8000/register, in your browser window.

完成注册功能后,您现在可以在浏览器窗口中转到注册URL http://127.0.0.1:8000/register 。

Create a testuser account.

创建一个testuser帐户。

If done correctly, you will be redirected to the homepage displaying the success message “Registration successful”.

如果操作正确,您将被重定向到显示成功消息“注册成功”的主页。

Now let’s check for the user information in the Django administration.

现在,让我们在Django管理中检查用户信息。

创建一个超级用户 (Create a superuser)

Terminal/Command Prompt

终端/命令提示

(env) C:\\Users\\Owner\\Desktop\\Code\\env\\mysite>py manage.py createsuperuser
Username (leave blank to use \'owner\'): owner
Email address:
Password: *****
Password (again): *****
Superuser created successfully.(env) C:\\Users\\Owner\\Desktop\\Code\\env\\mysite>py manage.py runserver

If you haven’t already, create a superuser account to gain access to the Django administration. We are going to check that the user was properly added to the database.

如果尚未创建超级用户帐户,则可以访问Django管理。 我们将检查用户是否已正确添加到数据库中。

Run the command

py manage.py createsuperuser

in Windows Command Prompt and

python3 manage.py createsuperuser

in Mac Terminal. Then fill out the username and password.

在Windows命令提示符中运行命令

py manage.py createsuperuser

,在Mac Terminal中运行

python3 manage.py createsuperuser

。 然后填写用户名和密码。

检查该用户是否在Django管理员中列出 (Check to see if the user is listed in the Django admin)

Go to the http://127.0.0.1:8000/admin/ URL where you will see a Django administration login.

转到http://127.0.0.1:8000/admin/ URL,您将在其中看到Django管理登录信息。

If you are still logged in as the testuser you will get the warning message “You are authenticated as testuser1, but are not authorized to access this page. Would you like to login to a different account?”.

如果您仍以测试用户身份登录,则将收到警告消息“您已通过测试用户1身份验证,但无权访问此页面。 您要登录其他帐户吗?”。

Yes, you do.

是的你是。

Login to the admin with your superuser account then click on “Users”. There you should see a list of all usernames and emails along with their staff status.

使用您的超级用户帐户登录到管理员,然后单击“用户”。 在这里,您应该会看到所有用户名和电子邮件的列表以及其工作人员身份。

用户登录 (User login)

Now you may have noticed the views function we created automatically logged a user in upon account creation. Be we want the user to have the ability to login freely. So we need a login template, URL, and views function.

现在您可能已经注意到,我们创建的视图功能会在创建帐户后自动登录用户。 是我们希望用户具有自由登录的能力。 因此,我们需要一个登录模板,URL和视图功能。

创建一个login.html文件 (Create a login.html file)

env > mysite > main > templates > main > (New File) login.html

env> mysite> main>模板> main>(新文件)login.html

{% extends \"main/header.html\" %}{% block content %}      {% load crispy_forms_tags %}<!--Login--> 
<div class=\"container py-5\">
<h1>Login</h1>
<form method=\"POST\">
{% csrf_token %}
{{ login_form|crispy }}
<button class=\"btn btn-primary\" type=\"submit\">Login</button>
</form>
<p class=\"text-center\">Don\'t have an account? <a href=\"/register\">Create an account</a>.</p>
</div>{% endfor %}

The basic structure of the HTML template is the similar to the register HTML. The only differences are the form and the link at the bottom.

HTML模板的基本结构与注册HTML相似。 唯一的区别是表格和底部的链接。

添加登录URL (Add a login URL)

env > mysite > main > urls.py

env> mysite> main> urls.py

from django.urls import path
from . import viewsapp_name = \"main\"
urlpatterns = [
path(\"\", views.homepage, name=\"homepage\"),
...
path(\"register\", views.register_request, name=\"register\"),
path(\"login\", views.login_request, name=\"login\")
]

Add a login path to the URLs.

将登录路径添加到URL。

在视图中添加登录功能 (Add a login function to the views)

env > mysite > main > views.py

env> mysite> main> views.py

from django.shortcuts import  render, redirect
from .forms import NewUserForm
from django.contrib.auth import login, authenticate #add this
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm #add thisdef register_request(request):
...def login_request(request):
if request.method == \"POST\":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get(\'username\')
password = form.cleaned_data.get(\'password\')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f\"You are now logged in as {username}.\")
return redirect(\"main:homepage\")
else:
messages.error(request,\"Invalid username or password.\")
else:
messages.error(request,\"Invalid username or password.\")
form = AuthenticationForm()
return render(request=request, template_name=\"main/login.html\", context={\"login_form\":form})

Now go back to views.py and add

authenticate

to the list of imports form

django.contrib.auth

then import

AuthenticationForm

from

django.contrib.auth.forms

at the top of the file.

现在回到views.py并添加

authenticate

进口的列表形式

django.contrib.auth

然后导入

AuthenticationForm

django.contrib.auth.forms

在文件的顶部。

AuthenticationForm is the pre-built Django form form logging in a user.

AuthenticationForm是登录用户的预建Django表单。

To write your login function, add an if/else statement that uses the Django function

authenticate()

. This function is used to verify user credentials (username and password) and return the correct User object stored in the backend.

要编写您的登录函数,请添加一个使用Django函数

authenticate()

的if / else语句。 此函数用于验证用户凭据(用户名和密码)并返回存储在后端的正确User对象。

If the backend authenticated the credentials, the function will run Django

login()

to login the authenticated user. Else if the user is not authenticated, it returns a message to the user stating they entered an invalid username or password.

如果后端对凭据进行了身份验证,则该函数将运行Django

login()

来登录经过身份验证的用户。 否则,如果用户未通过身份验证,它将向用户返回一条消息,指出他们输入了无效的用户名或密码。

The second else statement is if the form is not valid, then it returns a similar error message.

第二条else语句是,如果表单无效,则返回类似的错误消息。

The final else statement is if the request is not a POST, then return the blank form in the login HTML template.

最后的else语句是,如果请求不是POST,则在登录HTML模板中返回空白表格。

测试用户登录功能 (Test the user login functionality)

Now go to the login URL, http://127.0.0.1:8000/login, add login your testuser.

现在转到登录URL http://127.0.0.1:8000/login ,添加登录您的测试用户。

You will get the success message and be logged in if you entered the correct username and password.

如果输入正确的用户名和密码,您将获得成功消息并登录。

奖励:允许通过社交媒体帐户(例如,Facebook,Google,Twitter…)进行注册 (BONUS: Allow signups through social media accounts (i.e. Facebook, Google, Twitter …))

As of right now, the login is only available through Django’s built-in UserCreationForm but you can easy use django-alluth to quickly handle and create signup flows. This means users can create a user account using their social media accounts. You can follow that tutorial here.

到目前为止,登录仅可通过Django的内置UserCreationForm进行,但您可以轻松地使用django-alluth快速处理和创建注册流程。 这意味着用户可以使用其社交媒体帐户创建用户帐户。 您可以在此处遵循该教程。

用户注销 (User logout)

The last thing we need to handle is user logout. We will place the logout link in the navbar but it is only see by the user if they are authenticated (i.e. they are logged in).

我们需要处理的最后一件事是用户注销。 我们将注销链接放置在导航栏中,但只有经过身份验证(即已登录)的用户才能看到该链接。

<!--Navbar-->
<nav class=\"navbar navbar-expand-lg navbar-light bg-light\">
<a class=\"navbar-brand\" href=\"#\">Navbar</a>
<button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarText\" aria-controls=\"navbarText\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">
<span class=\"navbar-toggler-icon\"></span>
</button>
<div class=\"collapse navbar-collapse\" id=\"navbarText\">
<ul class=\"navbar-nav mr-auto\">
{% if user.is_authenticated %}

<li class=\"nav-item\">
<a class=\"nav-link\" href=\"/logout\">Logout</a>
</li>
<li class=\"nav-item\">
<a class=\"nav-link\" href=\"#\">Welcome, {{user.username}}</a>
</li> {% else %} <li class=\"nav-item\">
<a class=\"nav-link\" href=\"/login\">Login</a>
</li> {% endif %}
</ul>
</div>
</nav>

The Django template variable

{{ user }}

stores the current logged-in user and their permissions available in the template context.

Django模板变量

{{ user }}

存储当前登录用户及其在模板上下文中可用的权限。

All we need to do is add an if/else statement that if the user is authenticated show the logout link and their username, else show a login link.

我们需要做的就是添加一条if / else语句,如果用户通过身份验证,则显示注销链接及其用户名,否则显示一个登录链接。

This is a basic navigation bar from the Bootstrap documentation. If you are looking to further customize it, then refer to the article 10 Custom Bootstrap Navbars.

这是Bootstrap文档中的基本导航栏。 如果要进一步自定义它,请参阅文章10 Custom Bootstrap Navbars 。

添加注销URL (Add a logout URL)

env > mysite > main > urls.py

env> mysite> main> urls.py

from django.urls import path
from . import viewsapp_name = \"main\"
urlpatterns = [
path(\"\", views.homepage, name=\"homepage\"),
...
path(\"register\", views.register_request, name=\"register\"),
path(\"login\", views.login_request, name=\"login\"),
path(\"logout\", views.logout_request, name= \"logout\"),
]

Now add a logout URL path to the app’s URLs.

现在,将注销URL路径添加到应用程序的URL。

添加注销功能 (Add a logout function)

env > mysite > main > views.py

env> mysite> main> views.py

from django.shortcuts import  render, redirect
from .forms import NewUserForm
from django.contrib.auth import login, authenticate, logout #add this
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationFormdef register_request(request):
...def login_request(request):
...deflogout_request(request):
logout(request)
messages.info(request, \"You have successfully logged out.\")
return redirect(\"main:homepage\")

Finally, add a logout function to the views file. The

logout_request

function uses the Django function

logout()

to log the user out of their account and redirect them to the homepage when the logout URL is requested.

最后,向视图文件添加注销功能。

logout_request

函数使用Django函数

logout()

来注销用户的帐户,并在请求注销URL时将其重定向到首页。

测试用户注销功能 (Test the user logout functionality)

Go to the browser window and reload the page.

转到浏览器窗口,然后重新加载页面。

Login back in if you need to.

如果需要,请重新登录。

There should be a navbar with a logout link next to the welcome user text.

欢迎用户文本旁边应有一个带有注销链接的导航栏。

Click the logout link and the homepage should reload showing the logout message while only displaying a login link.

单击注销链接,主页应重新加载,显示注销消息,而仅显示登录链接。

如果用户忘记密码会怎样? (What happens if the user forgets their password?)

The last thing to think about are user password resets.

最后要考虑的是用户密码重置。

Django also handles this functionality using its authentication system.

Django还使用其身份验证系统处理此功能。

If you wish to learn how to allow users the ability to send a reset password to themselves, follow the tutorial Reset User Passwords in Django.

如果您想学习如何使用户能够向自己发送重置密码,请遵循Django中的重置用户密码教程。

Originally published at https://www.ordinarycoders.com.

最初发布在 https://www.ordinarycoders.com上 。

翻译自: https://levelup.gitconnected.com/a-guide-to-user-registration-login-and-logout-in-django-b6fde46b02d8

django用户注销

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » django用户注销_Django中的用户注册,登录和注销指南