How to automatically capitalize field on form submission in Django?

11,351

Solution 1

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)

Solution 2

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.

Solution 3

Use Python's capitalize() function.

edit:

see Jeremy Lewis' answer on where to use this function.

:)

Solution 4

If you want to ensure your data is consistent, I'm not sure that capitalizing at the form / view level is the best way to go.

What happens when you add a Product through the admin where you're not using that form / save method? If you forget the capital, you're in for data inconsistency.

You could instead use your model's save method, or even use the pre_save signal that django sends.

This way, data is always treated the same, regardless of where it came from.

Solution 5

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()
Share:
11,351
goelv
Author by

goelv

Updated on June 21, 2022

Comments

  • goelv
    goelv almost 2 years

    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!