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

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

添加'注册新用户'URL。

python 复制代码
#注册新用户
path('register/',views.register,name='register'),

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

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

python 复制代码
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这两项内容。

python 复制代码
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

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

添加'注册新用户'链接。

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 %}
相关推荐
第九序言T7 小时前
Python 数据处理进阶(十八)批量处理同结构文件:一个文件夹一次跑完
开发语言·python·自动化·pandas·数据处理
Java后端的Ai之路7 小时前
CAS并发控制-从CPU指令到企业级乐观锁
vue.js·人工智能·python·cas·乐观锁
qq_426003967 小时前
UI自动化高频次登录login限流解决方案
python·ui·自动化
Sakura_j_h_7 小时前
EasyEDA PCB 快速设计Skills
c++·python·github
学长毕设7 小时前
基于springboot的食品仓库管理系统
java·spring boot·后端
滴滴答答哒8 小时前
ASP.NET Core + FaceRecognitionDotNet 人脸识别实战:DI 单例、特征向量持久化与 1:N 比对
后端·asp.net
quantdash_cc8 小时前
如何验证历史行情的交易日期是否完整覆盖研究区间?
python·数据分析·pandas·量化交易·股票数据·quantdash
I Am a robert girl8 小时前
当智能体学会“串通”:从长程交互中读懂涌现式合谋
python·多智能体系统·多智能体协作·llm agent·涌现式合谋·对齐问题·激励机制设计
云和数据.ChenGuang9 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
专注仿真9 小时前
线性回归和逻辑回归算法详解
开发语言·人工智能·python·大模型训练·控制算法