Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django validate field based on value from another field

I have this django field called is_private indicating whether the posting done by the user is private or not. If the posting is private then a certain field called private_room must be mentioned otherwise a field called public_room is required.

In the clean_private_room and clean_public_room fields I'm doing a check to see the value of is_private. If the room is private then in the clean_public_room method I simply return an empty string "" and the same for clean_private_room otherwise I continue with the validation.

The problem is that checking with self.cleaned_data.get('is_private') is returning different results in those two methods. I tried debugging the code and printed the self.cleaned_data value to the terminal and in one of the methods cleaned data contains one form field and in the other method contains my full posted values.

Here's a part of my code, please read the comments in it to see where I print and what gets printed. I don't know why it's behaving this way.

class RoomForm( forms.ModelForm ):
    ...

    def clean_is_private( self ):
        if not 'is_private' in self.cleaned_data:
            raise forms.ValidationError("please select the type of room (private/public)")
        return self.cleaned_data.get("is_private")

    def clean_public_room( self ):
        print "<clean_public_room>"
        #   !!!!!!!!!
        #   when printing this one I only get one form value which is: public_room
        print self.cleaned_data

        if self.cleaned_data.get("is_private"):
            return ""

        #   otherwise....
        if not self.cleaned_data.get("public_room"):
            raise forms.ValidationError(
                'you need to mention a public room'
            )
        return self.cleaned_data[ 'public_room' ]

    def clean_private_room( self ):
        print "<clean_private_room>"
        #   !!!!!!!!!
        #   when printing this one I get all form values: public_room, private_room, is_private
        print self.cleaned_data

        if not self.cleaned_data.get("is_private"):
            return ""

        #   otherwise....
        if not self.cleaned_data.get("private_room"):
            raise forms.ValidationError(
                'you need to mention a private room'
            )
        return self.cleaned_data[ 'private_room' ]
like image 496
Romeo Mihalcea Avatar asked Dec 05 '25 14:12

Romeo Mihalcea


1 Answers

Form fields are cleaned in the order they defined in the form. So you just need to put is_private field before the public_room in the fields list.

like image 78
catavaran Avatar answered Dec 07 '25 03:12

catavaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!