Python 从0开始 一步步基于Django创建项目(11)注册新用户

04-06 1127阅读

1、修改C:\D\Python\Python310\study\snap_gram\users路径下的urls.py

Python 从0开始 一步步基于Django创建项目(11)注册新用户
(图片来源网络,侵删)

添加‘注册新用户’URL。

#注册新用户
path('register/',views.register,name='register'),

2、修改C:\D\Python\Python310\study\snap_gram\users路径下的views.py

编写URL对应的视图函数register。

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这两项内容。

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

{% extends "city_infos/base.html" %}
{% block content %}
    
    
        {% csrf_token %}
        {{ form.as_p }}
        注册
        
        
    
{% endblock content %}

4、修改C:\D\Python\Python310\study\snap_gram\city_infos\templates\city_infos路径下的base.html

添加‘注册新用户’链接。

{% if user.is_authenticated %}
    Hello,{{user.username}}.
    注销
{% else %}
    注册
    登录
{% endif %}
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]