I have a ProductForm
where users can add a Product
to the database with information like title
, price
, and condition
.
How do I make it so that when the user submits the form, the first letter of the title
field is automatically capitalized?
For example, if a user types "excellent mattress" in the form, django saves it as "Excellent mattress" to the database.
Just for reference, the reason I ask is because when I display all the product objects on a page, Django's sort feature by title is case-sensitive. As such, "Bravo", "awful", "Amazing" would be sorted as "Amazing", "Bravo", "awful" when as users, we know that is not alphabetical.
Thanks for the help!
Forms have a built-in hook for cleaning specific fields (docs), which would be a cleaner (pun intended) location for this code:
class ProductForm(forms.Form):
...
def clean_title(self):
return self.cleaned_data['title'].capitalize()
Far less code than the accepted answer, and no unnecessary overrides.
You could override the Model's save
method (which has the benefit of being able to concisely handle numerous fields in one place):
class Product(models.Model):
...
def save(self, *args, **kwargs):
for field_name in ['title', 'price', ... ]:
val = getattr(self, field_name, False)
if val:
setattr(self, field_name, val.capitalize())
super(Product, self).save(*args, **kwargs)
Use Python's capitalize()
function.
see Jeremy Lewis' answer on where to use this function.
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With