我在使用django时遇到了麻烦。由于某些愚蠢的原因,Django想要说我不能将选择作为表单的一部分。它顽固地说,
'用户'对象没有属性'选择'
哪个是公牛,因为我没有提到用户对象。我不知道如何解决这个问题。我只需要从表单中选择选择的视图方法。有谁知道怎么做?
这是表格......
''' Form used in medical personnel registration. Extends UserCreationForm '''
class MedicalPersonnelRegisterForm(UserCreationForm):
#email = EmailField(required = True)
choices = [
(Nurse, 'Nurse'),
(Doctor, 'Doctor'),
(HospitalAdmin, 'Admin'),
]
position = forms.ChoiceField(choices = choices)
class Meta:
model = User
fields = ("username", "password1", "password2")
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())
if commit:
user.save()
return user
视图看起来像这样......
''' This displays the Medical personnel login form. Unique because of radio box for type of user '''
def personnel_registration(request):
if request.method == "POST":
form = MedicalPersonnelRegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
if new_user.choices == Nurse: # TODO : THIS MIGHT BREAK BADLY
new_nurse = Nurse(user = new_user)
new_nurse.save()
temp = Event(activity= '\n'+new_nurse.user.get_full_name()+" has registered as a Nurse")
temp.save()
elif new_user.choices == Doctor:
new_doctor = Doctor(user = new_user)
new_doctor.save()
temp = Event(activity= '\n'+new_doctor.user.get_full_name()+" has registered as a Doctor")
temp.save()
else:
new_admin = HospitalAdmin(user = new_user)
new_admin.save()
temp = Event(activity= '\n'+new_admin.user.get_full_name()+" has registered as a Admin")
temp.save()
return HttpResponseRedirect('/login/') # TODO : Refer them to there home page
else:
form = MedicalPersonnelRegisterForm()
return render(request, "main_site/personnel_registration.html", {
"form" : form,
})
答案 0 :(得分:1)
你这里有很多混乱的地方,所以很难解开你真正想要的东西。
首先,您应该注意错误发生的位置:在视图中,而不是在表单中。在它发生时,您有一个User模型的实例。它在任何地方都没有choices
属性。
其次,即使您正在查看表单,您仍然没有任何名为choices
的内容。您使用选项为position
字段设置允许值和用户可读内容,但choices
本身不是字段。
由于position
是表单上的额外字段,与User模型无关,因此您需要从表单数据本身获取它,该表单数据位于form.cleaned_data
中。所以:
if form.cleaned_data['position'] == Nurse:
...