goelv
goelv

Reputation: 2884

How to automatically capitalize field on form submission in Django?

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!

Upvotes: 7

Views: 14646

Answers (6)

V.k. Sulaiman
V.k. Sulaiman

Reputation: 41

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()

Upvotes: 1

olleugra
olleugra

Reputation: 21

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"

Upvotes: 0

lciamp
lciamp

Reputation: 685

Use Python's capitalize() function.

edit:

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

:)

Upvotes: 2

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

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)

Upvotes: 13

Thomas Orozco
Thomas Orozco

Reputation: 55293

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.

Upvotes: 1

Jeremy Lewis
Jeremy Lewis

Reputation: 1719

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.

Upvotes: 26

Related Questions