gpt4 book ai didi

python - 如何在 Django 中向 UserCreationForm 添加字段?

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:09 25 4
gpt4 key购买 nike

所以我一直在做一个 Django 项目,但遇到了死胡同。每次我尝试修改 UserCreationForm 以说明保险 ID 和/或提供商时,我都会遇到一个错误,提示我无法执行此操作:

Unknown field(s) (Insurance Provider, Insurance ID) specified for User

我想知道是否有人可以告诉我如何将这些字段添加到表单中而不必覆盖我的用户类?

''' Form used in patient registration. Extends UserCreationForm '''
class PatientRegisterForm(UserCreationForm):
email = EmailField(required = True)
insurance_id = forms.CharField(required=True, label="Insurance ID")
insurance_provider = forms.CharField(required=True, label="Insurance Provider")

class Meta:
model = User
fields = ("email", "password1", "password2", "Insurance ID", "Insurance Provider")

def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2

def save(self, commit=True):
user=super(UserCreationForm, self).save(commit=False)
user.set_password(self.clean_password2())
user.insurance_id = self.cleaned_data["insurance_id"]
user.insurance_provider = self.cleaned_data["insurance_provider"]
if commit:
user.save()
return user

''' This displays the patient login form. Unique because of insurance numbers '''
def patient_registration(request):
if request.POST:
form = PatientRegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
new_patient = Patient(user = new_user)
new_patient.save()
temp= Event(activity= '\n'+new_patient.user.get_full_name()+" has registered as a patient ")
temp.save()
return HttpResponseRedirect('/login/') # TODO : Refer them to there home page
else:
return HttpResponseRedirect('/login/') # TODO : Ditto ^^^
else:
form = PatientRegisterForm()
return render(request, "main_site/patient_registration.html", {"form":form})

最佳答案

您没有正确引用表单中的 insurance_idinsurance_provider 字段。将 Meta 类更改为:

class Meta:
model = User
fields = ("email", "password1", "password2", "insurance_id", "insurance_provider")
# Note: the last two fields have changed

您还需要在 User 模型中定义 insurance_idinsurance_provider

关于python - 如何在 Django 中向 UserCreationForm 添加字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33511250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com