I have a form with which I want to update a MyModel object. On the model there is a unique_together constraint, fieldA together with fieldB. In the form in the clean method I check for this unique constraint.
For some reasons I have to show fieldA as readonly in the update. Thus fieldA is not passed through. My issue is that if the form does not validate, the form is re-shown, but I have lost the value in fieldA.
I tried to reset the cleaned_data['fieldA'], but it does not work. Any idea what to change?
Forms.py
class MyModelUpdateForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyModelUpdateForm, self).__init__(*args, **kwargs)
self.fields['fieldA'].widget.attrs['readonly'] = True
self.fields['fieldA'].widget.attrs['disabled'] = True
def clean(self):
cleaned_data = self.cleaned_data
fieldA= self.instance.fieldA
fieldB = cleaned_data.get("fieldB")
if MyModel.objects.filter(fieldA=fieldA, fieldB=fieldB).count() > 0:
#try to reset fieldA, since it is not passed through, since it is disabled
cleaned_data['fieldA'] = fieldA.pk #does not work
raise forms.ValidationError('some unique validation error')
return cleaned_data
Views.py:
myModelobject = get_object_or_404(MyModel.objects, pk=mymodel_id)
if request.method == 'POST':
model_form = MyModelUpdateForm(request.POST, instance=myModelobject )
if model_form .is_valid():
....