How to automatically capitalize field on form submission in Django?

Viewed 12276

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!

6 Answers

You can use clean method in models, ie:

class Product(models.Model):
    title = models.CharField(max_length=30)
    ...
    def clean(self):
        self.title = self.title.capitalize()

if you need all first letters of all words to capitalize use val.title() in Jeremy Lewis' answer. If you use val.capitalize() then "hello world" would be "Hello world", with title() you can get "Hello World"

Related