django - 通过表单在 Django 中创建用户
问题描述
我想在 Django 中有一个用户注册表单,我知道对于后端我应该有这样的东西:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
>>> user.last_name = 'Lennon'
>>> user.save()
但是,我不知道如何制作前端。我已经在 Django 文档中查找并找到了UserCreationForm 类,它说它已被弃用。我应该怎么办?谢谢
解决方案
尝试这样的事情:
#forms.py
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
您应该阅读Django 文档中有关身份验证的这一部分。
推荐阅读
- c# - 使用 iText 导出为 PDF 不显示来自 GridView 的完整数据
- reactjs - 在 react.js 中使用 API 获取数据
- caching - Neo4j 整个图未加载到页面缓存中
- nlp - 如何创建NLP(自然语言处理领域语言)模型.....?
- javascript - 我需要更换在字符串中标记该标记 java 脚本中的内容
- python-3.x - Nonetype 对象没有属性“用户”
- graphql - 有没有办法从 graphql.js 解析器的信息重建查询?
- scadalts - 备份无法运行
- routes - 我有一个关于 react-router v4 的问题,我不明白
- react-native - 获取错误不变违规:试图注册两个具有相同名称的视图