获取额外的数据到django表单下拉列表选择 [英] Get additional data into django form dropdown selection

查看:186
本文介绍了获取额外的数据到django表单下拉列表选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Action模型,它有一个外键,它指定一个动作重现的频率:

I have an Action model that has a foreign key which specifies how often an action reoccurs:

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")

制作一个ActionForm的Action,导致重现的HTML代码(基于Reoccurance表中存在的数据库值):

I'm making a modelForm of Action that results in HTML code for reoccurance (based on the database values that exist for the Reoccurance table):

<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>

正如你所看到的,虽然选择是按升序排列,但是这些值是无序的,因为他们被按顺序输入数据库。

As you can see, though the selections are in ascending day order, the values are out of order because they were entered into the database out of order.

我想创建一些动态计算动作重新生成日期的jquery。它将采取今天的日期,并添加与用户选择的选择相对应的天数。但是,随着我收到的数据,我无法将选择转换成设定的天数。即使期权项目的价值是有序的,仍然不表示说1年等于365天。

I want to create some jquery that dynamically calculates the date when the action will reoccur. It will take today's date and add the number of days that correspond to the selection that the user has chosen. But with the data I get in the form, I cannot translate the selection into a set number of days. Even if the values of the option items were in order, it still doesn't indicate that say "1 Year" is equal to 365 days.

这个数据是在重现表中。对于label =1年,days = 365.同样对于重现表中的所有项目。

This data though is in the Reoccurance table. For label = "1 Year", days = 365. Likewise for all of the items in the Reoccurance table.

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

Is there a way to rewrite my modelForm so that perhaps the option value of each drop down item is equal to the number of days for that selection? Because then, I could access the number of days:

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

这是否会不利地影响我将正确重现的选择与重现表的正确行相结合的能力?有没有另一种方式可以在我的表单模板中使用jquery这个日子/标签领带?

Would this adversely affect my ability to tie the proper reoccurance selection to the correct row of the Reoccurance table? Is there another way I can access this days/label tie in jquery on my form template?

更新

感谢Joseph的建议,检查这篇文章,我可以在我的选项元素中包含一个标题:

Thanks to Joseph's suggestion to check this post, I was able to include a title in my option element:

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)

太棒了所以现在我在我的模板中得到以下内容:

Fantastic. So now I get the following in my template:

<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中,我尝试以下选项来获取选项的标题:

Ok, it seems like we're almost there, but I'm getting tripped up. In the jquery, I'm trying the following to get the title of the option selected:

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

问题是它是未定义的!

更新获得

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


推荐答案

摆脱这个问题/答案(这是粗糙的,未经测试,希望开始):

Basing off this question/answer (and this is rough, not tested, hopefully a start):

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

这篇关于获取额外的数据到django表单下拉列表选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆