I found 4 (easy) possible solutions to this problem.
The most valid solution for Django is this:
class TheFormName():
client_id = forms.CharField(show_hidden_initial=True, widget=forms.HiddenInput())
identifier = forms.CharField(show_hidden_initial=True, widget=forms.HiddenInput())
def clean(self):
if self.has_changed():
raise forms.ValidationError('Fields are not valid.')
return self.cleaned_data
The second solution is by using the changed_data
to see what has changed:
def clean(self):
for field_name in self.changed_data:
# loop through the fields which have changed
print "field {} has changed. New value {}".format(field_name, cleaned_data['field_name']
For my case is translated to this, but is exactly the same as the has_changed()
method:
def clean(self):
if len(self.changed_data) > 0:
raise forms.ValidationError('Fields are not valid.')
return self.cleaned_data
Another solution that looks more like a hack is:
self.cleaned_data['cliend_id'] == self.instance.cliend_id
self.cleaned_data['identifier'] == self.instance.identifier
And the final solution a bit more complex is by using sessions inside clean()
method (and outside of view). Example from Django Docs:
from django.contrib.sessions.backends.db import SessionStore
import datetime
s = SessionStore()
s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
s.save()
s.session_key
>>> '2b1189a188b44ad18c35e113ac6ceead'
s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
s['last_login']
Also useful is this post In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected? provided by @LarsVegas