django positiveinteger空白的默认值

时间:2014-09-23 23:13:18

标签: django django-models default

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

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 =&#39;&#39; 纳入ACHIEVEMENT_TYPES。

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

我有两个问题:

1。如何替换&#39; ---------&#39;的默认文本?使用&#39;选择成就类型&#39;

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

1 个答案:

答案 0 :(得分: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.')},
    }
    ....