python 通过 Django 管理站点添加数据时更改大小写(大写/小写)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/825955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing case (upper/lower) on adding data through Django admin site
提问by Andor
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
编辑:好的,我知道 .upper 属性,我做了一个视图,我知道该怎么做,但我想知道管理站点上的字段配置是否有任何可用的属性:P
回答by wbyoung
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 validationto 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 savein 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)
回答by Damon
Updated example from documentation suggests using args, kwargs to pass through as:
文档中的更新示例建议使用 args、kwargs 作为传递:
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.
Django 会不时扩展内置模型方法的功能,添加新参数。如果您在方法定义中使用 *args、**kwargs,则可以保证您的代码在添加这些参数时会自动支持这些参数。
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()
回答by Javier
you have to override save(). An example from the documentation:
你必须覆盖 save()。文档中的一个例子:
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()