I have a ModelForm object for an UpdateView and I want to find a way to validate using def clean_start(self):
if the start date was altered when the form was submitted. I have found data_changed but this just lists the fields that have changed, not what the values were before and after. Please can I have a pointer to what I should be doing?
class EventEditForm(ModelForm):
class Meta:
model = Event
fields = ['name', 'start', 'end', 'description', 'organiser_contact',
'team_event', 'active', 'oop_active', 'oop_coded', 'cancelled']
labels = {'active': 'Event Public',
'oop_active': 'Order of Play Published',
'logo': 'Event Logo',
'oop_coded': 'Restricted Access'}
widgets = {
'start': forms.DateTimeInput(format=('%Y-%m-%dT%H:%M'), attrs={'type': 'datetime-local'}),
'end': forms.DateTimeInput(format=('%Y-%m-%dT%H:%M'), attrs={'type': 'datetime-local'})
}
def clean_start(self):
# How do I get the value of start when the form was first rendered and compare to
# the value of start now?
I believe (but am not sure) that the original value would be available as self.instance.start
. The current value is in self.cleaned_data['start']
.
form support changed_data(list[str]).
form = EventEditForm(initial={'start': {some}}, data={some})
form.is_vaild()
'start' in form.changed_data
@KenWhitesell your belief was correct - thank you.
@white-seolpyo I’m now realising that I also need to find the field differences in the form_valid() method and I think what you have written is a clue to that but I can’t believe I have to create the form in the first place with a copy of the original data in order to then compare the data returned to form_valid? Surely the original data used to generate the form must be somewhere and then changed_data can be used to identify which fields to look at for changes ? I’m trying to stick to form validation being in the forms.py and actions based on change being inside views.py. Any pointers gratefully received.
I don’t understand what you want to say.
Could you please convey this clearly and easily?
I’m not sure if you’re still looking for an answer to this question, but if so, the answer is no.
Keep in mind that each instance of your view is a new invocation. There is no persistence of data or objects between when you create the bare instance of the form for the GET and when you recreate the instance to bind the submitted data in the POST.