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 %}
相关推荐
wn5319 分钟前
【Go - 类型断言】
服务器·开发语言·后端·golang
Narutolxy19 分钟前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
希冀12333 分钟前
【操作系统】1.2操作系统的发展与分类
后端
Amo Xiang42 分钟前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
liangbm31 小时前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
GoppViper1 小时前
golang学习笔记29——golang 中如何将 GitHub 最新提交的版本设置为 v1.0.0
笔记·git·后端·学习·golang·github·源代码管理
B站计算机毕业设计超人1 小时前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~1 小时前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
serve the people2 小时前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端