django positiveinteger 默认值为空白

Posted

技术标签:

【中文标题】django positiveinteger 默认值为空白【英文标题】:django positiveinteger default value of blank 【发布时间】:2014-09-23 23:13:18 【问题描述】:

我有一个带有选择列表/正整数字段的模型类。

class AchievementDetails(models.Model, FillableModelWithLanguageVersion):
    ACADEMIC_ACHIEVEMENT = 1
    COMMERCIAL_ACHIEVEMENT = 2
    PERSONAL_ACHIEVEMENT = 3
    PROFESSIONAL_ACHIEVEMENT = 4
    SPORTING_ACHIEVEMENT = 5
    OTHER_ACHIEVEMENT_TYPE = 6

ACHIEVEMENT_TYPES = (
    (ACADEMIC_ACHIEVEMENT, _('Academic Details')),
    (COMMERCIAL_ACHIEVEMENT, _('Commercial Achievement')),
    (PERSONAL_ACHIEVEMENT, _('Personal Achievement')),
    (PROFESSIONAL_ACHIEVEMENT, _('Professional Achievement')),
    (SPORTING_ACHIEVEMENT, _('Sporting Achievement')),
    (OTHER_ACHIEVEMENT_TYPE, _('Other Achievement Type')),
)

....
achievement_type = models.PositiveIntegerField(choices=ACHIEVEMENT_TYPES)
....

上述设置添加了以下选择列表选项作为默认选项:

<option value="">---------</option>

我被指示不要将 SELECT_TYPE = '' 包含在 ACHIEVEMENT_TYPES 中。

我使用django-parsley 进行客户端验证,因此选项值必须为空值。

我有两个问题:

1.如何将“------”的默认文本替换为“选择成就类型”

2。当表单在编辑模板中时,如何删除默认选项值?

【问题讨论】:

【参考方案1】:

我让这个工作使用:

validators=[MinValueValidator(1)]

我是这样用的:

在 models.py 文件中包含导入:

from django.core.validators import MinValueValidator

将具有零值的类型包含到models.py文件中:

SELECT_ACHIEVEMENT_TYPE = 0
ACADEMIC_ACHIEVEMENT = 1
COMMERCIAL_ACHIEVEMENT = 2
PERSONAL_ACHIEVEMENT = 3
PROFESSIONAL_ACHIEVEMENT = 4
SPORTING_ACHIEVEMENT = 5
OTHER_ACHIEVEMENT_TYPE = 6
WRITE_MY_OWN_ACHIEVEMENT_TYPE_DESCRIPTION = 7777  # 7777 triggers a hidden text field to be displayed.
DISPLAY_ONLY_ACHIEVEMENT_DESCRIPTION_WITH_PROMPT = 8888
DISPLAY_ONLY_ACHIEVEMENT_DESCRIPTION_WITHOUT_PROMPT = 9999

ACHIEVEMENT_TYPES = (
    (SELECT_ACHIEVEMENT_TYPE, _('Select Type')),
    (ACADEMIC_ACHIEVEMENT, _('Academic Achievement')),
    (COMMERCIAL_ACHIEVEMENT, _('Commercial Achievement')),
    (PERSONAL_ACHIEVEMENT, _('Personal Achievement')),
    (PROFESSIONAL_ACHIEVEMENT, _('Professional Achievement')),
    (SPORTING_ACHIEVEMENT, _('Sporting Achievement')),
    (OTHER_ACHIEVEMENT_TYPE, _('Other Achievement Type')),
    (WRITE_MY_OWN_ACHIEVEMENT_TYPE_DESCRIPTION, _('Write my own Type description')),
    (DISPLAY_ONLY_ACHIEVEMENT_DESCRIPTION_WITH_PROMPT, _('Display only Description with prompt')),
    (DISPLAY_ONLY_ACHIEVEMENT_DESCRIPTION_WITHOUT_PROMPT, _('Display only Description without prompt'))
)

在 models.py 文件中包含选项、默认值和 MinValueValidator 的字段:

 ....
 achievement_type = models.PositiveIntegerField(choices=ACHIEVEMENT_TYPES, default=SELECT_ACHIEVEMENT_TYPE, validators=[MinValueValidator(1)])
 ....

在 forms.py 文件中,包含 error_messages 元数据以覆盖错误消息(对于 Django 1.5+):

    .....
    error_messages = 
        'achievement_type': 'validate_min': _('This field is required.'),
    
    ....

【讨论】:

以上是关于django positiveinteger 默认值为空白的主要内容,如果未能解决你的问题,请参考以下文章

[codeforces722D]Generating Sets

Django 设置默认日志记录

怎样设置django默认的url

django 默认时区设置

Django model.py表单的默认值 默认允许为空

重命名默认的 django 表