Django ModelForm custom validation: How to access submitted field values
Asked Answered
L

1

11

I have the below model form and want to add custom validation to a field called 'billable_work'.

How do I access a field 'project' which was submitted in the form? I want to check the value of project ('p' in the below example) but can't locate the proper syntax so that I can test the submitted value. Any help would be appreciated.

class EntryForm(forms.ModelForm):
    class Meta:
        model = Entries
        exclude = ('billable_work','notes')  

    billable_work = forms.BooleanField()
    notes = forms.CharField(widget=forms.Textarea,required=False)

    def clean_billable_work(self):
        b = self.cleaned_data['billable_work']
        p = form.fields['project']

        if b == True and p == 523:
            raise forms.ValidationError(_("Entries cannot be both billable and NONE: Indirect."))
        return self.cleaned_data['billable_work']
Lyallpur answered 26/2, 2013 at 17:16 Comment(0)
E
18

I think you want to override the clean() method on your model rather than the clean method of a specific form field. From the docs -

This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field.

If you did want to put the validation in the form then the clean() method on the form provides similar functionality (see docs).

Ertha answered 26/2, 2013 at 17:29 Comment(2)
Thanks for the link in the docs. I was looking for the syntax self.cleaned_data.get('project'). In order to test the value I have to convert this to a string. Is this a proper/valid method?Lyallpur
Interesting note-- I'm working to add custom validation to an admin form. Docs for Django 3.1 point out the clean() method does not run for admin interface, and you must use forms.Uvarovite

© 2022 - 2024 — McMap. All rights reserved.