Django form: restore predefined field value in clean method
<p>In my Django form I need to perform different field values comparisons (+ some additional checks). If all of these conditions are met I want to raise error and inform user that he can't perform this operation. Right now I'm doing it in <code>clean</code> method and code looks like these: </p>

<pre><code>        if self.instance.foo != cleaned_data['foo'] and \
            Bar.objects.filter(baz=self.instance.id).count():
        cleaned_data['foo'] = self.instance.foo
        raise forms.ValidationError("You can't change it")
</code></pre>

<p>That's working fine, but I'd also like to reject the change and restore previous value (before the update). The assignment <code>cleaned_data['foo'] = self.instance.foo</code> obviously is not working because cleaned_data is not being returned due to raising ValidationError. How can I achieve this?</p>

<p>It turned out that you can access fields' values via <code>self.data</code>. So I ended up doing <code>self.data['foo'] = self.instance.foo</code> and it's working now.</p>

python django django-forms