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 %}
相关推荐
苍何8 小时前
开源微信流 Windows,微信聊天记录,可以直接给 Codex 和 Obsidan 了
后端
代码什么用9 小时前
Spring基础使用
java·后端·spring
明月_清风10 小时前
Deno 终局来了:从挑战 Node 到被 Cloudflare 收编
前端·后端·node.js
蜗牛互联网10 小时前
Java 17 HttpClient调用文件转写API的超时与失败回退
java·人工智能·后端
全栈练习生11 小时前
AI Agent 沙箱
python·ai
SEO_juper12 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户693717500138412 小时前
2026,程序员的时代拐点到了
android·前端·后端
惜鸟12 小时前
从源码看 pi 的上下文管理:原始数据永久保留,模型视角按需裁剪
后端
量化分析码农13 小时前
【Python量化策略评估体系 #05】极端行情扛得住吗?2008/2015/2020 三场景压力测试
后端
十年Java程序媛13 小时前
Java 接口和抽象类对比|Java8 新特性,抛弃老旧八股,正确选型
java·spring boot·后端