Posts

Showing posts with the label Learning Django

Python Django - Self.data vs Self.cleaned_data

Image
By understanding how the attributes  self.cleaned_data  and  self.data  work and how to get its values, you can control and use them efficiently in your forms. DEFINING THE FORM This is a simple ModelForm example for a model named Car. I created the  clean_price  method to change the original format of the  price  field that will be passed to the form. This is particularly important, because it’s a key to understand the difference between  self.cleaned_data  and  self.data . class CarForm(ModelForm): price = forms.CharField(max_length=20) class Meta: model = Car fields = ['name','brand','color','price'] def clean_price(self): price = self.cleaned_data['price'] price = re.sub('[.]', '', price) price = re.sub('[,]', '.', price) return price PASSING DATA TO THE FORM The first thing to do is to create a dictionary and pass to the form as the f