将附加数据获取到 django 表单下拉选择中

2024-05-06

我有一个具有外键的操作模型,它指定操作重复发生的频率:

class Reoccurance(models.Model):
    label = models.CharField("Label", max_length=50, unique = True)
    days = models.IntegerField("Days")

    def __unicode__(self):
        return self.label

    class Meta:
        ordering = ['days']

class Action(models.Model):
    name = models.CharField("Action Name", max_length=200, unique = True)
    complete = models.BooleanField(default=False, verbose_name="Complete?")
    reoccurance = models.ForeignKey(Reoccurance, blank=True, null=True, verbose_name="Reoccurance")

我正在制作一个 Action 的 modelForm,它会生成用于重复出现的 HTML 代码(基于“重复出现”表中存在的数据库值):

<select id="id_reoccurance" class="select" name="reoccurance">
    <option value="" selected="selected">---------</option>
    <option value="12">2 Days</option>
    <option value="1">3 Days</option>
    <option value="2">5 Days</option>
    <option value="10">6 Days</option>
    <option value="9">1 Week</option>
    <option value="3">10 Days</option>
    <option value="4">2 Weeks</option>
    <option value="11">3 Weeks</option>
    <option value="5">1 Month</option>
    <option value="13">6 Weeks</option>
    <option value="6">1 Quarter</option>
    <option value="7">6 Months</option>
    <option value="8">1 Year</option>
</select>

正如您所看到的,虽然选择是按日期升序排列的,但这些值是无序的,因为它们是无序输入到数据库中的。

我想创建一些 jquery 来动态计算该操作再次发生的日期。它将采用今天的日期并添加与用户选择的选项相对应的天数。但根据我在表单中获得的数据,我无法将选择转换为设定的天数。即使选项项的值是按顺序排列的,也并不表示“1 年”等于 365 天。

但该数据位于“重复发生”表中。对于标签 =“1 年”,天数 = 365。对于“重复发生”表中的所有项目也是如此。

有没有办法重写我的 modelForm,以便每个下拉项的选项值可能等于该选择的天数?因为那时,我可以访问天数:

$("#id_reoccurance").change(function() {
    alert( $(this).val() );
});

这是否会对我将正确的重复发生选择与重复发生表的正确行联系起来的能力产生不利影响?有没有其他方法可以在我的表单模板上使用 jquery 访问 this days/label tie ?

Update

感谢约瑟夫的建议检查这个帖子 https://stackoverflow.com/questions/5089396/django-form-field-choices-adding-an-attribute,我能够在我的选项元素中包含一个标题:

from django.utils.html import conditional_escape, escape
from django.utils.encoding import force_unicode

class SelectWithTitles(forms.Select):
    def __init__(self, *args, **kwargs):
        super(SelectWithTitles, self).__init__(*args, **kwargs)
        # Ensure the titles dict exists
        self.titles = {}

    def render_option(self, selected_choices, option_value, option_label):
        title_html = (option_label in self.titles) and \
            u' title="%s" ' % escape(force_unicode(self.titles[option_label])) or ''
        option_value = force_unicode(option_value)
        selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
        return u'<option value="%s"%s%s>%s</option>' % (
            escape(option_value), title_html, selected_html,
            conditional_escape(force_unicode(option_label)))

class ChoiceFieldWithTitles(forms.ChoiceField):
    widget = SelectWithTitles

    def __init__(self, choices=(), *args, **kwargs):
        choice_pairs = [(c[0], c[1]) for c in choices]
        super(ChoiceFieldWithTitles, self).__init__(choices=choice_pairs, *args, **kwargs)
        self.widget.titles = dict([(c[1], c[2]) for c in choices])

class ActionForm(forms.ModelForm):
    reoccurance = ChoiceFieldWithTitles()

    def __init__(self, *args, **kwargs):
        super(ActionForm, self).__init__(*args, **kwargs)   

        choices = []
        for pt in Reoccurance.objects.all():
            choices.append((pt.id, pt.label, pt.days))
        self.fields['reoccurance'] = ChoiceFieldWithTitles(choices = choices)

极好的。所以现在我在我的模板中得到以下内容:

<select id="id_reoccurance" class="selectwithtitles" name="reoccurance">
    <option value="12" title="2" >2 Days</option>
    <option value="1" title="3" >3 Days</option>
    <option value="2" title="5" >5 Days</option>
    <option value="10" title="6" >6 Days</option>
    <option value="9" title="7" >1 Week</option>
    <option value="3" title="10" >10 Days</option>
    <option value="4" title="14" >2 Weeks</option>
    <option value="11" title="21" >3 Weeks</option>
    <option value="5" title="30" >1 Month</option>
    <option value="13" title="42" >6 Weeks</option>
    <option value="6" title="90" >1 Quarter</option>
    <option value="7" title="180" >6 Months</option>
    <option value="8" title="365" >1 Year</option>
</select>

好吧,看来我们快到了,但我被绊倒了。在 jquery 中,我尝试执行以下操作来获取所选选项的标题:

$(function() {
    $("#id_reoccurance").change(function() {
        alert($(this).attr('title'));
    }); 
});

问题是它返回为未定义!

Update Got it

$(function() {
    $("#id_reoccurance").change(function() {
        alert($(this).find("option:selected").attr("title"));
    }); 
});

基地关闭这个问题/答案 https://stackoverflow.com/questions/3700445/add-additional-options-to-django-form-select-widget(这是粗糙的,未经测试,希望是一个开始):

class myClassForm(forms.Form):
    class Meta:
        model = myClass
        fields=["name"]

    reoccurrance = forms.ChoiceField(label="Reoccurance", choices=(),
                                   widget=forms.Select(attrs={'class':'selector'}))


def __init__(self, *args, **kwargs):
    super(myClassForm, self).__init__(*args, **kwargs)
    choices = []
    for pt in Reoccurance.objects.all():
      choices.append((pt.id, unicode(pt.days)))
    self.fields['reoccurrance'].choices = choices
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将附加数据获取到 django 表单下拉选择中 的相关文章

随机推荐