2015-11-03 34 views
1

所以我一直在研究一個Django項目,並且我已經陷入了死衚衕。每次我試圖修改UserCreationForm佔保險ID和/或供應商的時候,我打,說我不能做這樣的錯誤:如何在Django中將字段添加到UserCreationForm?

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}) 

回答

1

您沒有正確參照您的形式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

相關問題