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

丶灬走出姿态 提交于 2019-12-03 16:25:21

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

Updated example from documentation suggests using args, kwargs to pass through as:

Django will, from time to time, extend the capabilities of built-in model methods, adding new arguments. If you use *args, **kwargs in your method definitions, you are guaranteed that your code will automatically support those arguments when they are added.

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        do_something()
        super(Blog, self).save( *args, **kwargs) # Call the "real" save() method.
        do_something_else()

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!