Python + Django4 to build a personal blog (15): Implementation of registration function page

In the previous article, we implemented user login and logout.

In this article, we improve another important function of user management: registration.

Write registration form class

When a user registers, a form will be used to submit data such as account number, password, etc., so a registration form needs to be written /userprofile/forms.py:

# 注册用户表单
class UserRegisterForm(forms.ModelForm):
    # 复写 User 的密码
    password = forms.CharField()
    password2 = forms.CharField()

    class Meta:
        model = User
        fields = ('username', 'email')

    # 对两次输入的密码是否一致进行检查
    def clean_password2(self):
        data = self.cleaned_data
        if data.get('password') == data.get('password2'):
            return data.get('password')
        else:
            raise forms.ValidationError("密码输入不一致,请重试。")

As mentioned in the previous chapter, the form that operates the database should inherit forms.ModelForm, which can automatically generate fields already in the model.

Here we have overwritten passwordthe field, because it is usually necessary to re-enter it during registration passwordto ensure that the user has not entered the password incorrectly, so we overwrite it so that we can verify the data ourselves. def clean_password2()The content is to verify whether the password is consistent. def clean_[字段]This way of writing Django will automatically call it to verify and clean the data of a single field.

After overriding a field, class Metathe definition in the inner class has no effect on this field, so fields do not need to be included password.

requires attention:

The method to verify password consistency cannot be written def clean_password(), because if you do not define def clean_password2()the method, password2the data in it will be Djangojudged as invalid data and will be cleaned, so that password2the attributes will not exist. Eventually, the two password inputs will always be inconsistent, and it will be difficult to determine the cause of the error.

POSTThe value obtained from it data.get('password')is written in a safe way. Even if the user does not enter a password, it will not cause a program error and jump out. We used it to extract POST data in the previous chapter data['password']. If this value method datais not included password, Djangoan error will be reported. Another way to prevent users from submitting without entering a password is to insert requiredattributes into the form, which will be discussed later.

view function

Write the registered view /userprofile/views.py:

# 用户注册
def user_register(request):
    if request.method == 'POST':
        user_register_form = UserRegisterForm(data=request.POST)
        if user_register_form.is_valid():
            new_user = user_register_form.save(commit=False)
            # 设置密码
            new_user.set_password(user_register_form.cleaned_data['password'])
            new_user.save()
            # 保存好数据后立即登录并返回博客列表页面
            login(request, new_user)
            return redirect("list")
        else:
            return HttpResponse("注册表单输入有误。请重新输入~")
    elif request.method == 'GET':
        user_register_form = UserRegisterForm()
        context = { 'form': user_register_form }
        return render(request, 'userprofile/register.html', context)
    else:
        return HttpResponse("请使用GET或POST请求数据")

It logically combines the published article view and the user login view , and there is no new knowledge.

After successful registration, the user will automatically log in and return to the blog list page.

templates and urls

We are also familiar with the template files related to forms. Here we involve two templates writing and processing.

1. Add registration page

Newtemplates/userprofile/register.html

{% extends "base.html" %} {% load static %}
{% block title %} 注册 {% endblock title %}
{% block content %}
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-6">
            <br>
            <form method="post" action=".">
                {% csrf_token %}
                <!-- 账号 -->
                <div class="form-group">
                    <label for="username">昵称</label>
                    <input type="text" class="form-control" id="username" name="username" required>
                </div>
                <!-- 邮箱 -->
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="text" class="form-control" id="email" name="email">
                </div>
                <!-- 密码 -->
                <div class="form-group">
                    <label for="password">设置密码</label>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>
                <!-- 确认密码 -->
                <div class="form-group">
                    <label for="password2">确认密码</label>
                    <input type="password" class="form-control" id="password2" name="password2" required>
                </div>
                <br>
                <!-- 提交按钮 -->
                <button type="submit" class="btn btn-primary btn-block">提交</button>
            </form>
        </div>
    </div>
</div>
{% endblock content %}

In the template file above, we input added requiredattributes (mentioned earlier) to the nickname and password tags. If the user does not fill in requiredthe fields with the attribute, the form cannot be submitted and the user is prompted to fill it out. In fact, many of the forms learned earlier can add requiredattributes to verify the validity of the data in advance.

2. Add registration entrance

Add registration entry to the login page /templates/userprofile/login.html:

       <div class="form-group">
            <br>
            <h5>还没有账号?</h5>
            <h5>点击<a href='{% url "register" %}'>注册账号</a>加入我们吧!</h5>
        <br>
        </div>

The last step is to configure the routing file django4blog/urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', article.views.hello),
    re_path(r'^$', article.views.article_list),
    path('list/', article.views.article_list, name='list'),  # 展示文章
    path('detail/<int:id>/', article.views.article_detail, name='detail'),  # 文章详情
    path('create/', article.views.article_create, name='create'),  # 写文章
    path('delete/<int:id>/', article.views.article_delete, name='delete'),# 删除文章
    path('update/<int:id>/', article.views.article_update, name='update'),    # 更新文章
    path('login/', userprofile.views.user_login, name='login' ),
    path('logout/', userprofile.views.user_logout, name='logout' ),
# 增加注册管理
    path('register/', userprofile.views.user_register, name='register' ),
]

test

Run the server and enter the login page. There is a registration prompt:

Click Register Account to enter the registration page:

Submit after filling out the form (email address can be empty):

After successfully logging in and returning to the blog list, the function is completed.

Summarize

This chapter uses form classes, data verification and cleaning, and other knowledge to complete the user registration function.

At this point, we have basically implemented the core user login, logout, and registration functions.

Next we will learn another important module: comment management.

Guess you like

Origin blog.csdn.net/agelee/article/details/126966234
Recommended