I have this form to register a user, but the clean of the age field tells me that the form does not have this attribute
class RegistrarPersonaIndependieteForm(UserCreationForm):
....
edad = forms.IntegerField(required=True)
class Meta:
model = Usuario
fields = ['username', 'email', 'password1', 'password2', 'sector_economico', 'celular',
'first_name', 'last_name', 'tipo_identificacion', 'edad']
def __init__(self, *args, **kwargs):
super(RegistrarPersonaIndependieteForm, self).__init__(*args, **kwargs)
....
self.fields['edad'].widget.attrs['class'] = 'input is-large'
def clean_edad(self):
from dubs2.desarrollo_empresarial.validators import edad_empleado_valida
try:
edad_empleado_valida(self.edad)
except Exception:
raise ValidationError('No se encuentra en el rango de edades permitidas')
return self.edad
You have to access the attribute
cleaned_data
, said attribute is to access the already validated and "clean" form data, if the data is not validated, the dictionarycleaned_data
contains only the valid fields:That fixes your problem.
On the other hand, if you are in doubt as to why the attribute does not exist
edad
(something that seemed strange to me, so I replicated your code and got the same error), it is because that is how the Django developers programmed or developed it, and this can be seen in the metaclassDeclarativeFieldsMetaclass
:The metaclass
ModelFormMetaclass
inherits from said metaclass and in turn is the metaclass of the classModelForm
:The reasons why they did so, I do not know and I think it is not necessary to know.
I hope I've helped.