Thursday, May 5, 2011

Changing case (upper/lower) on adding data through Django admin site

I'm configuring the admin site of my new project, and I have a little doubt on how should I do for, on hitting 'Save' when adding data through the admin site, everything is converted to upper case...

Edit: Ok I know the .upper property, and I I did a view, I would know how to do it, but I'm wondering if there is any property available for the field configuration on the admin site :P

From stackoverflow
  • you have to override save(). An example from the documentation:

    class Blog(models.Model):
        name = models.CharField(max_length=100)
        tagline = models.TextField()
    
        def save(self, force_insert=False, force_update=False):
            do_something()
            super(Blog, self).save(force_insert, force_update) # Call the "real" save() method.
            do_something_else()
    
  • If your goal is to only have things converted to upper case when saving in the admin section, you'll want to create a form with custom validation to make the case change:

    class MyArticleAdminForm(forms.ModelForm):
        class Meta:
            model = Article
        def clean_name(self):
            return self.cleaned_data["name"].upper()
    

    If your goal is to always have the value in uppercase, then you should override save in the model field:

    class Blog(models.Model):
        name = models.CharField(max_length=100)
        def save(self, force_insert=False, force_update=False):
            self.name = self.name.upper()
            super(Blog, self).save(force_insert, force_update)
    

0 comments:

Post a Comment