Validating a Django model field based on another field's value?
<p>I have a Django app with models accessible by both Django REST Framework and a regular form interface. The form interface has some validation checks before saving changes to the model, but not using any special Django framework, just a simple local change in the view.</p>

<p>I'd like to apply the same validation to forms and REST calls, so I want to move my validation into the model. I can see how to do that for simple cases using the validators field of the Field, but in one case I have a name/type/value model where the acceptable values for 'value' change depending on which type is selected. The validator doesn't get sent any information about the model that the field is in, so it doesn't have access to other fields.</p>

<p>How can I perform this validation, without having essentially the same code in a serializer for DRF and my POST view for the form?</p>

<p>The validation per-field doesn't get sent any information about other fields, when it is defined like this:</p>

<pre><code>def validate_myfield(self, value):
    ...
</code></pre>

<p>However, if you have a method defined like this:</p>

<pre><code>def validate(self, data):
    ...
</code></pre>

<p>Then you get all the data in a dict, and you can do cross-field validation.  </p>

python django forms validation