我有一个简单的表单来向网站添加网站。这是我的网站模型:
class Site(models.Model):
category = models.ForeignKey('Category')
category1 = models.ForeignKey('Category', related_name='+',)
subcategory = ChainedForeignKey(
'Subcategory',
chained_field='category',
chained_model_field='category',
show_all=False,
auto_choose=True)
name = models.CharField(max_length=70)
description = models.TextField()
# importuje zmienione TextFields widgets.py
keywords = MyTextField()
date = models.DateTimeField(default=datetime.now, editable=False)
url = models.URLField()
is_active = models.BooleanField(default=False)
group = models.CharField(max_length=2, choices=(('Basic',
'Basic'), ('Premium', 'Premium')))
subcategory1 = ChainedForeignKey(
'Subcategory',
chained_field='category1',
chained_model_field='category1',
related_name='subcategory1',
show_all=False,
auto_choose=True)
def get_absolute_url(self):
return "%s/%i" % (self.subcategory.slug, self.id)
class Meta:
verbose_name_plural = "Sites"
def __str__(self):
return self.name
Forms.py
class SiteAddFormFull(forms.ModelForm):
url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))
class Meta:
model = Site
fields = ('url', 'name', 'description', 'keywords', 'group', 'category1','subcategory1')
我想通过添加字段'类别1','子类别1'来更改我的表单。用户在组字段中选择值后(' Premium')。表单应重新加载并显示这些字段。在选择' Premium'之前字段'类别1','子类别1'应该是看不见的。我怎样才能做到这一点?
在我的forms.py中,我添加了:
widgets = {'category1': forms.HiddenInput(), 'subcategory1':
forms.HiddenInput()}
在我的.js文件中,我尝试显示这些字段,但它不起作用:
$(":hidden").show();
// $("#id_category1".show() and other posibilities
在我的页面中,我有
<input id="id_category1" name="category1" type="hidden" /><input id="id_subcategory1" name="subcategory1" type="hidden" />
为什么它不起作用?
答案 0 :(得分:0)
您不需要HiddenInput
类别。只需用jquery隐藏它,并在select change事件中显示它。
<select id="group">
<option value="First">First</option>
<option value="Premium">Premium</option>
<option value="Second">second</option>
</select>
<select id="category1">
<option value="First">First</option>
<option value="Second">second</option>
</select>
Jquery的
$(document).ready(function(){
$('#category1').hide();
$('#group').change(function(e) {
var group = $(this).val();
if (group == 'Premium'){
$('#category1').show();
} else {
$('#category1').hide();
}
});
});