我有一个下面定义的注册表格
forms.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
class SignUpForm(UserCreationForm):
display_name = forms.CharField(max_length=30, required=True, help_text='Please provide a display name for your profile')
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'display_name')
在views.py中,我处理了注册过程
views.py
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from .forms import SignUpForm
from django.shortcuts import render, redirect
@csrf_exempt
def signup_users(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data.get('username')
display_name = form.cleaned_data.get('display_name')
raw_password = form.cleaned_data.get('password1')
user.set_password(raw_password)
user.display_name = display_name
user.save()
user = authenticate(username=username, password=raw_password)
print("signup authencticate", user)
login(request, user)
return render(request, 'index.html')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
用户能够成功注册,但是他们的display_name
不会存储在django用户模型中。即使在django管理员中,我也看不到字段display_name
。我什至执行了像serializers.serialize("json",User.objects.filter(username=username))
这样的查询,但即使在这里它也会显示除display_name
之外的所有其他字段。
我在做什么错了?
答案 0 :(得分:2)
很简单,django.contrib.auth.models.User
模型没有名为display_name
的字段,因此当然不会保存它。如果要向用户模型添加字段,则必须provide a custom User model。