I'm not sure if I'm implementing the clean and the clean_<fieldname> methods correctly. In the documentation it says that we should call them, but where? we have to call them because at the moment of trying to go through form.is_valid() the data comes out as not validated and my question would be what I have to do heres my model:
class Users(models.Model):
USERNAME_FIELD = models.CharField(max_length=90, blank=False, null=False, primary_key=True)
LASTNAME_FIELD = models.CharField(max_length=90, null=False, blank=False)
USERAGE_FIELD = models.IntegerField(null = True )
USER_IMAGE_FIELD = models.ImageField(null = True, blank = False, upload_to='media/')
USERMAIL_FIELD = models.EmailField()
USERPSSWD_FIELD = models.CharField(max_length= 100)
CONFPSSWD_FIELD = models.CharField(max_length=100)
def clean(self):
if (len(self.USERNAME_FIELD) = 0):
raise ValidationError(_(not empty space'))
def __str__(self):
return self.USERNAME_FIELD
and heres my forms:
from django import forms
from .models import Users
from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _
from django.forms import formset_factory
from django.core.exceptions import ValidationError
class Usersform(forms.ModelForm):
class Meta:
model = Users
fields = '__all__'
labels = {
'USERNAME_FIELD': _('Nombre del Usuario:'),
'LASTNAME_FIELD': _('Apellido del Usuario'),
'USERAGE_FIELD': _('Edad del Usuario:'),
'USER_IMAGE_FIELD': _('Foto del Usuario:'),
'USERMAIL_FIELD': _('Email del Usuario:'),
'USERPSSWD_FIELD': _('Contraseña:'),
'CONFPSSWD_FIELD': _('Confirma la Contraseña:'),
}
def clean_USERAGE_FIELD(self):
data = self.cleaned_data['USERAGE_FIELD']
if (data < 18):
raise ValidationError('you cant sign up youre to young')
return data
def clean_USERMAIL_FIELD(self):
data = self.cleaned_data['USERMAIL_FIELD']
if (len(data) == 0 ):
raise ValidationError('no empty spaces')
return data
def clean(self):
cleaned_data = super(Usersform, self).clean()
self.USERNAME_FIELD = cleaned_data.get("USERNAME_FIELD")
self.LASTNAME_FIELD = cleaned_data.get("LASTNAME_FIELD")
self.USER_IMAGE_FIELD = cleaned_data.get("USER_IMAGE_FIELD")
self.USERPSSWD_FIELD = cleaned_data.get("USERPSSWD_FIELD")
self.CONFPSSWD_FIELD = cleaned_data.get("CONFPSSWD_FIELD")
if (self.USERPSSWD_FIELD != self.CONFPSSWD_FIELD):
raise ValidationError("pass no coincide")
return cleaned_data
and heres my view :
class Sign_UpView(View):
template_name = "register.html"
form_class = Usersform
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
print(request.POST)
if form.is_valid():
try:
form.clean()
HttpResponse('redirected')
except:
print("error")
return render(request, self.template_name, {'form':form})
please i need help