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 %}
相关推荐
qq_336313931 分钟前
java基础-IO流(随机点名器)
java·开发语言·python
liu****2 分钟前
深度学习简介
人工智能·python·深度学习·python基础
无垠的广袤4 分钟前
【工业树莓派 CM0 NANO 单板计算机】基于舵机和人脸识别的智能门禁系统
linux·python·opencv·yolo·ai·树莓派
guchen665 分钟前
CircularBuffer 优化历程:从数组越界到线程安全的完美实现
后端
大学生毕业题目5 分钟前
毕业项目推荐:102-基于yolov8/yolov5/yolo11的行人车辆检测识别系统(Python+卷积神经网络)
人工智能·python·yolo·目标检测·cnn·pyqt·行人车辆检测
古城小栈6 分钟前
Cargo.toml
开发语言·后端·rust
嫂子的姐夫9 分钟前
017-续集-贝壳登录(剩余三个参数)
爬虫·python·逆向
4***175414 分钟前
Python 小游戏实战:打造视觉精美的数独小游戏
开发语言·python·pygame
悟空码字15 分钟前
10分钟搞定!SpringBoot集成腾讯云短信全攻略,从配置到发送一气呵成
java·spring boot·后端
星浩AI15 分钟前
从0到1:用LlamaIndex工作流构建Text-to-SQL应用完整指南
人工智能·后端·python