我有一个 Action 模型,它有一个外键,它指定了一个 Action 重复发生的频率:
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")
我正在制作一个 modelForm of Action,它会生成用于重现的 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 天。
尽管此数据位于 Reoccurance 表中。对于标签 =“1 年”,天数 = 365。对于 Reoccurance 表中的所有项目也是如此。
有没有办法重写我的 modelForm,使每个下拉项的选项值可能等于该选择的天数?因为那时,我可以访问天数:
$("#id_reoccurance").change(function() {
alert( $(this).val() );
});
这是否会对我将正确的重现选择与重现表的正确行相关联的能力产生不利影响?有没有其他方法可以在我的表单模板上访问 this days/label tie in jquery?
更新
感谢Joseph建议查看this post ,我能够在我的选项元素中包含一个标题:
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'));
});
});
问题是它返回时未定义!
更新 知道了
$(function() {
$("#id_reoccurance").change(function() {
alert($(this).find("option:selected").attr("title"));
});
});
最佳答案
基于 this question/answer (这是粗略的,未经测试,希望是一个开始):
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
关于jquery - 将其他数据获取到 django 表单下拉选择中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306841/
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge
我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c
我安装了ruby版本管理器,并将RVM安装的ruby实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby。有没有办法让emacs像shell一样尊重ruby的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el