Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 947
goelv Avatar asked Aug 16 '12 23:08

goelv


3 Answers

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.

like image 152
Jeremy Lewis Avatar answered Nov 16 '22 02:11

Jeremy Lewis


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)
like image 24
Timmy O'Mahony Avatar answered Nov 16 '22 03:11

Timmy O'Mahony


Use Python's capitalize() function.

edit:

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

:)

like image 37
lciamp Avatar answered Nov 16 '22 02:11

lciamp