如何在Django中为用户创建注册表单 [英] How to create a register form for Users in Django

查看:93
本文介绍了如何在Django中为用户创建注册表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django创建用户的方式是什么?
我不是在谈论超级用户,只是一个简单的用户表单和创建帐户

What is the Django way of creating a User? I am not talking about the super user, just a simple form for users and creating an account

推荐答案

Django docs很好地涵盖了身份验证主题,并且Django本身附带了用于登录,注销,密码更改和重置的视图。对于注册,您必须创建自己的视图,如下所示:

The Django docs cover the topic of authentication quite well, and Django itself ships with views for login, logout, password change, and reset. For registration, you'll have to create your own view, something like this:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render

def create_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("User created successfully!")
    else:
        form = UserCreationForm()
        return render(request, 'auth/create_user.html', {'form': form})

这使用Django的内置用户创建表单,该表单需要一个用户名和两个密码来进行验证。您的模板如下所示:

This uses Django's built-in User creation form, which expects a username and two passwords, for verification. Your template would look something like this:

<form action='/create-user/' method='post'>
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

这篇关于如何在Django中为用户创建注册表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆