[Fixed]-Django Form Validators on Comparing One Object Against Another

1👍

Firstly, you should subclass ModelForm, not BaseModelForm. Write a clean_<fieldname> method for your user_signature field, and make sure that the value is as expected. You can access self.instance.created_by to check.

class NonDisclosureForm(ModelForm):
    ...

    class Meta:
        model = NonDisclosure
        fields = ['user_signature', ...]

    def clean_user_signature(self):
        user_signature = self.cleaned_data['user_signature']
        expected_name = '%s %s' % (self.instance.created_by.first_name, self.instance.created_by.last_name)
        if user_signature != expected_name:
            raise forms.ValidationError('Signature does not match')
        return user_signature

Then you need to update your view so that it sets instance.created_by. You can do this by overriding get_form_kwargs.

class NdaCreate(CreateView):

    def get_form_kwargs(self):
        kwargs = super(NdaCreate, self).get_form_kwargs()
        kwargs['instance'] = NonDisclosure(created_by=self.request.user)
        return kwargs

Leave a comment