我正在尝试将UserCreationForm额外字段中的数据添加到数据库中,我想将多个字段添加到UserCreationForm中并将其保存到数据库中。我在stackoverflow上看到了其他主题的示例,但这是行不通的。
这是我的代码示例: (字段:“ agree_terms”或“ price”可以是其他任何内容)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(widget = forms.EmailInput(attrs=
{'placeholder':'Email'}))
agree_terms = forms.BooleanField()
price = forms.DecimalField(decimal_places=2, max_digits=10000)
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('username', 'password1',
'email','password2','agree_terms','price')
views.py
@csrf_protect
def registers(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
print(form)
print(form.is_valid())
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request,'Conta criada {}'.format(username))
return redirect('login')
else:
form = UserRegisterForm()
return render(request,'header-login.html',{'form':form})
答案 0 :(得分:0)
您是否还更改了User
模型以支持这些字段?您还需要将它们添加到模型/表中。
尽管如此,我不建议直接在User
模型上堆积太多额外的数据。