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 %}
相关推荐
小鸡吃米…21 小时前
机器学习 - 精确率与召回率
人工智能·python·机器学习
sonrisa_21 小时前
Python同一类不同方法中变量值的传递
开发语言·windows·python
毕设源码-邱学长21 小时前
【开题答辩全过程】以 基于Springboot的酒店住宿信息管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
逻极21 小时前
OpenClaw「Clawdbot/Moltbot」 深入解析:核心架构深度剖析
python·ai·架构·agent·ai编程·moltbot·openclaw
sayang_shao1 天前
C++ ONNX Runtime 与 Python Ultralytics 库实现 YOLOv8 模型检测的区别
c++·python·yolo
曹牧1 天前
Java:强类型转换
开发语言·python
爱学习的阿磊1 天前
Python入门:从零到一的第一个程序
jvm·数据库·python
naruto_lnq1 天前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
仟濹1 天前
【Java加强】1 异常 | 打卡day1
java·开发语言·python
Dingdangcat861 天前
基于RetinaNet的建筑表面缺陷检测与识别系统研究_2
python