2014-11-02 64 views
0

我試圖驗證模型窗體,但我收到此錯誤The Member could not be created because the data didn't validate.失敗的行是employee = form.save(commit = False)由於數據未驗證,無法創建Django ValueError對象

這裏是我的形式:

class EmployeeForm(forms.ModelForm): 
    class Meta: 
     model = Member 
     fields = ['first_name', 'last_name', 'customer_code', 'address1', 'address2', 'city', 'state', 'zip_code', 'telephone'] 

    def __init__(self, *args, **kwargs): 
     super(EmployeeForm, self).__init__(*args, **kwargs) 
     self.fields['first_name'].widget = TextInput(attrs={ 
      'placeholder': 'First Name'}) 
     self.fields['last_name'].widget = TextInput(attrs={ 
      'placeholder': 'Last Name'}) 
     self.fields['customer_code'].widget = TextInput(attrs={ 
      'placeholder': 'Customer Code'}) 
     self.fields['address1'].widget = TextInput(attrs={ 
      'placeholder': 'Address'}) 
     self.fields['address2'].widget = TextInput(attrs={ 
      'placeholder': 'Address Line 2'}) 
     self.fields['city'].widget = TextInput(attrs={ 
      'placeholder': 'City'}) 
     self.fields['state'].widget = TextInput(attrs={ 
      'placeholder': 'State'}) 
     self.fields['zip_code'].widget = TextInput(attrs={ 
      'placeholder': 'Zip Code'}) 
     self.fields['telephone'].widget = TextInput(attrs={ 
      'placeholder': 'Telephone'}) 

    def is_valid(self): 
     #super(EmployeeForm, self).clean() 
     if 'customer_code' in self.errors: 
      del self._errors['customer_code'] 
     return self 

這是我的觀點:

@login_required 
def employee_register(request): 
    if request.method == 'POST': 
     form = EmployeeForm(request.POST) 
     if form.is_valid(): 
      print "FORM IS VALID" 
      employee = form.save(commit = False) 
      code = employee.customer_code 
      try: 
       employer = Member.objects.get(customer_code = code) 
       print "GOT EMPLOYER" 
       employee.employer = employer 
      except ObjectDoesNotExist: 
       print "NO EMPLOYER FOUND" 
       error = "The customer code entered does not match a valid customer in our database." 
       return render_to_response('app/employee_register.html', {'form' : form, 'error' : error}, context_instance = RequestContext(request)) 
      employee.user = request.user 
      employee.role = "Attendee" 
      employee.customer_code = None 
      employee.save() 
      print "SAVED USER" 

      return HttpResponseRedirect(reverse('app:mainRouter')) 
     else: 
      print "FORM NOT VALID" 
      return render_to_response('app/employee_register.html', {'form' : form}, context_instance = RequestContext(request)) 
    else: 
     form = EmployeeForm() 
     return render_to_response('app/employee_register.html', {'form' : form}, context_instance = RequestContext(request)) 

和我的模型:

class Member(models.Model): 
    first_name = models.CharField(max_length = 30) 
    last_name = models.CharField(max_length = 30) 
    user = models.OneToOneField(User, null = False) 
    email = models.EmailField(null = False) 
    address1 = models.CharField(max_length=100) 
    address2 = models.CharField(max_length=100, blank=True, null = True) 
    city = models.CharField(max_length=100) 
    state = models.CharField(max_length=2) 
    zip_code = models.CharField(max_length=5) 
    country = models.CharField(max_length=50, null = True, blank = True) 
    telephone = models.CharField(max_length = 15) 


    role_choices = (
     ('Attendee', 'Attendee'), 
     ('Customer', 'Customer'), 
     ('Registrar', 'Registrar'), 
     ('Area Coordinator', 'Area Coordinator'), 
     ('Admin', 'Admin'), 
     ('Sales', 'Sales'), 

     ) 

    role = models.CharField(choices = role_choices, max_length = 50) 
    employer = models.ForeignKey('Member', null = True, blank = True) 
    ## ATTENDEE FIELDS 

    #employer_code = models.CharField(max_length = 50, null = True) 
    electrosign = models.BooleanField(default = False) 

    ##CUSTOMER FIELDS 
    customer_code = models.CharField(max_length = 50, null = True, unique = True, blank = True) 
    insurance = models.ForeignKey('Insurance', null = True, blank = True) 


    def __unicode__(self): 
     name = self.first_name + self.last_name 
     return name 

我不知道這個問題可能是什麼,我在嘗試保存對象之前檢查表單is_valid()。所有的幫助/建議表示感謝,謝謝。

回答

0

您必須不是覆蓋is_valid

您已經完成它的方式,您從is_valid返回self,並且既然不是None,False或空字符串或列表,它將被視爲True:因此您的表單總是「有效」。

自定義驗證的正確方法是覆蓋clean方法,這就是你應該在這裏做的;來自clean的正確返回值是self.cleaned_data