【问题标题】:How to make a RadioSelect non manditory and remove default option in a ModelForm?如何使 RadioSelect 非强制并删除 ModelForm 中的默认选项?
【发布时间】:2015-05-13 15:14:16
【问题描述】:

编辑我的问题与可能的重复问题不同的原因是因为这并没有解决使其非 manditory 同时还删除了默认选项“-------”

我想在forms.ModelForm 中提出一个RadioSelect 调查问题非强制性

要使用RadioSelect,我将在我的ModelForm(下)中添加小部件,因为Djangos 模型不提供RadioSelectSelect 小部件。

执行此操作的标准方法是将Blank=True 作为参数传递。然而,正如我在另一个问题中发现的那样,我问了it turns out that if you pass blank=True as an argument from models.CharField to the forms.RadioSelect widget it will leave the default option "-------" in place even if you use default=None.

我必须删除默认选项“-------”。

那么,如何在不包括默认选项“-------”的同时使 RadioSelect 问题成为非强制性问题?

谢谢

forms.py

class SurveyFormB(forms.ModelForm): 

    class Meta:
        model = Person
        fields = ['internet_usage', 'smart_phone_ownership', 'smart_phone_usage']        

        widgets = {'internet_usage' : forms.RadioSelect,
                   'smart_phone_ownership' : forms.Select,
                   'smart_phone_usage' : forms.RadioSelect,
                   }

models.py

#How often do you use the Internet?  
INTERNET_LESS_THAN_ONE_HOUR_A_DAY = 'Less than one hour per day'
INTERNET_ONE_TO_TWO_HOURS_A_DAY = '1 - 2 hours per day'
INTERNET_TWO_TO_FOUR_HOURS_A_DAY = '2 - 4 hours per day'
INTERNET_FOUR_TO_SIX_HOURS_A_DAY = '4 - 6 hours per day'
INTERNET_SIX_TO_EIGHT_HOURS_A_DAY = '6 - 8 hours per day'
INTERNET_EIGHT_PLUS_HOURS_A_DAY = '8 + hours per day'

INTERNET_USAGE = (
    (INTERNET_LESS_THAN_ONE_HOUR_A_DAY, 'Less than one hour a day'),
    (INTERNET_ONE_TO_TWO_HOURS_A_DAY, '1 - 2 hours a day'),
    (INTERNET_TWO_TO_FOUR_HOURS_A_DAY, '2 - 4 hours a day'),
    (INTERNET_FOUR_TO_SIX_HOURS_A_DAY, '4 - 6 hours a Day'),
    (INTERNET_SIX_TO_EIGHT_HOURS_A_DAY, '6 - 8 hours a day'),
    (INTERNET_EIGHT_PLUS_HOURS_A_DAY, '8 + hours a day'),
           )

internet_usage = models.CharField(null=True, max_length=100, default=None, choices=INTERNET_USAGE, verbose_name='How long do you spend on the Internet each day?')

【问题讨论】:

  • 深思熟虑,您创建选择INTERNET_USAGE 的方式并不理想。首先,元组具有相同的值,并且仍然定义了两次字符串以及The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.
  • 谢谢,我一直在努力改进这一点。我不是 100% 确定你的意思,你能举个例子吗?
  • 当然,可以这样想:INTERNET_USAGE = ( ('One', 'Less than one hour a day'), ('Two', '1 - 2 hours a day'), ('Three', '2 - 4 hours a day'),......) 现在,当您获得One 的值时,它表示第一个,Two 选择了第二个选项,依此类推。
  • 所以使用这个解决方案我可以删除前几行,例如INTERNET_LESS_THAN_ONE_HOUR_A_DAY = 'Less than one hour per day' ?这将大大减少我的代码。
  • 你能显示你添加了什么,那不起作用吗?因为它可以在任何地方添加,但只需确保将widgets = {'internet_usage' : forms.RadioSelect, ... 更改为widgets = {'internet_usage' : RadioSelectNotNull, ... 确保您有正确的导入语句

标签: django django-models django-forms


【解决方案1】:

考虑NickJ 的答案并使用RadioSelectNotNull 如下:

forms.py

from itertools import chain
from django.forms import RadioSelect
from django.utils.encoding import force_unicode

class RadioSelectNotNull(RadioSelect):

    def get_renderer(self, name, value, attrs=None, choices=()):
        """Returns an instance of the renderer."""
        if value is None: value = ''
        str_value = force_unicode(value) # Normalize to string.
        final_attrs = self.build_attrs(attrs)
        choices = list(chain(self.choices, choices))
        if choices[0][0] == '':
            choices.pop(0)
        return self.renderer(name, str_value, final_attrs, choices)


class SurveyFormB(forms.ModelForm): 

    class Meta:
        model = Person
        fields = ['internet_usage', 'smart_phone_ownership', 'smart_phone_usage']        

        widgets = {'internet_usage' : RadioSelectNotNull,
                   'smart_phone_ownership' : forms.Select,
                   'smart_phone_usage' : RadioSelectNotNull,
                   }

请注意,如果您还可以将选项字段修改为:

models.py

INTERNET_USAGE = (
    ("One", 'Less than one hour a day'),
    ( "Two", '1 - 2 hours a day'),
    ( "Three", '2 - 4 hours a day'),
    ( "Four", '4 - 6 hours a Day'),
    ( "Five", '6 - 8 hours a day'),
    ( "Six", '8 + hours a day'),
)

internet_usage = models.CharField(null=True, max_length=100, default=None, choices=INTERNET_USAGE, verbose_name='How long do you spend on the Internet each day?')

【讨论】:

  • get_renderer 不再是东西(使用 Django 3.2)
猜你喜欢
  • 2010-10-12
  • 2018-07-17
  • 1970-01-01
  • 2018-05-22
  • 2020-11-20
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多