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 %}
相关推荐
minstbe1 小时前
IC设计私有化AI助手实战:基于Docker+OpenCode+Ollama的数字前端综合增强方案(进阶版)
人工智能·python·语言模型·llama
zyq99101_12 小时前
优化二分查找:前缀和降复杂度
数据结构·python·蓝桥杯
qyzm2 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
月月玩代码2 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
XPoet3 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程
码事漫谈3 小时前
从“功能实现”到“深度优化”:金仓数据库连接条件下推技术的演进之路
后端
Qt学视觉3 小时前
AI2-Paddle环境搭建
c++·人工智能·python·opencv·paddle
码事漫谈4 小时前
数据库查询优化中的谓词下推策略与成本感知优化实践
后端
Amour恋空4 小时前
SpringBoot+Lombok+Logback实现日志
spring boot·后端·logback
廋到被风吹走4 小时前
【LangChain4j】特点功能及使用场景
后端·python·flask