[Fixed]-Getting error object has no attribute 'get' while using clean in django modelform

1👍

You should return cleaned data from clean() method or raise error. You are not doing that.

class StudentForm(forms.ModelForm):

    class Meta:
        model = Student
        fields = '__all__'

    def clean(self):
        batch_start_year = self.cleaned_data.get('batch_start_year',None)
        # do something
        return self.cleaned_data
👤Rohan

0👍

If you want to validate all your form, you can use clean method like this

class StudentForm(forms.ModelForm):

    class Meta:
        model = Student
        fields = '__all__'

    def clean(self):
        cleaned_data = super(StudentForm, self).clean()
        batch_start_year = cleaned_data.get('batch_start_year')

In this case, you do not need to return anything. You will just raise validation error. If you want to validate some specific field, you will do it like this

def clean_field_name(self):
    data = self.cleaned_data.get('field_name')
    if "something" not in data:
        raise forms.ValidationError("Validation message")

    # Always return the cleaned data, whether you have changed it or
    # not.
    return data

Another possibility of error can be the way you are sending data to your form

student = Student.objects.get(pk=id)
form = StudentForm(intention) # An unbound form

The first argument to a form is the data but you are passing the instance. To properly pass the instance you should use:

student = Student.objects.get(pk=id)
form = StudentForm(instance=student) #

Leave a comment