Python 从0开始 一步步基于Django创建项目(11)注册新用户

发布于:2024-03-29 ⋅ 阅读:(15) ⋅ 点赞:(0)

1、修改C:\D\Python\Python310\study\snap_gram\users路径下的urls.py

添加‘注册新用户’URL。

#注册新用户
path('register/',views.register,name='register'),

2、修改C:\D\Python\Python310\study\snap_gram\users路径下的views.py

编写URL对应的视图函数register。

def register(request):
    if request.method != 'POST':
        form = UserCreationForm()
    else:
        # 处理填写好的表单
        form = UserCreationForm(data=request.POST)

        if form.is_valid():
            new_user = form.save()
            # 让用户自动登录,再重定向到主页。
            login(request,new_user)
            return redirect('city_infos:index')

    # 显示空表单或指出表单无效。
    context = {'form':form}
    return render(request,'registration/register.html', context)

该函数中使用了UserCreationForm表单类,以及login()方法。需要再文件中import这两项内容。

from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm

3、新建C:\D\Python\Python310\study\snap_gram\users\templates\registration路径下的register.html

<!-- 一个应用程序中的模板可继承另一个应用程序中的模板 -->
{% extends "city_infos/base.html" %}

{% block content %}
    <!-- 对提交的注册信息进行处理 -->
    <form method="post" action="{% url 'users:register' %}">
        {% csrf_token %}
        {{ form.as_p }}<!-- 显示表单内容 -->
        <button name="submit">注册</button>
        <!-- next:登录后重定向 -->
        <input type="hidden" name="next"
               value="{% url 'city_infos:index' %}" />
    </form>
{% endblock content %}

4、修改C:\D\Python\Python310\study\snap_gram\city_infos\templates\city_infos路径下的base.html

添加‘注册新用户’链接。

{% if user.is_authenticated %}
    Hello,{{user.username}}.
    <a href="{% url 'users:custom_logout' %}">注销</a>
{% else %}
    <a href="{% url 'users:register' %}">注册</a>
    <a href="{% url 'users:login' %}">登录</a>
{% endif %}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到