apardes
apardes

Reputation: 4380

Django ValueError Object could not be created because the data didn't validate

I'm trying to validate a modelform but I'm receiving this error The Member could not be created because the data didn't validate. The line where is fails is employee = form.save(commit = False).

Here is my form:

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

And here's my view:

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

and my model:

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

I am not sure what the issue could be, I am checking that the form is_valid() before trying to save the object. All help/suggestions is appreciated, thanks.

Upvotes: 3

Views: 6687

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

You must not override is_valid.

The way you've done it, you return self from is_valid, and since that is not None, False or an empty string or list, it is considered True: so your form is always "valid".

The proper way to customize validation is to override the clean method, and that is what you should do here; the proper return value from clean is self.cleaned_data.

Upvotes: 1

Related Questions