我有以下情况,我有这个模型:
class Profile(models.Model):
DEVELOPER = 1
MARKETER = 2
ACADEMIC = 3
INFLUENCER = 4
COMMUNITY_MEMBER = 5
ROLE_CHOICES = (
(DEVELOPER, 'Developer'),
(MARKETER, 'Marketer'),
(ACADEMIC, 'Academic'),
(INFLUENCER, 'Influencer'),
(COMMUNITY_MEMBER, 'Community Member'),
)
user = models.OneToOneField(User)
account_type = models.ForeignKey(AccountType, default=AccountType.FREE)
role = models.PositiveIntegerField(choices=ROLE_CHOICES, null=True, blank=True)
github_profile = models.URLField(blank=True, null=True)
linkedin_profile = models.URLField(blank=True, null=True)
现在我想做的是,如果用户点击下拉菜单中的Developer
选项,github_profile应该会出现,否则它应该保持隐藏状态。
现在,看起来像这样,Github链接字段应该是隐藏的:
这是我的html:
<div class="form-group select-wrapper">
<label for="role">What best describes you?</label>
<select id="role" name="role" class="form-control">
<option selected>Choose an option</option>
{% for index, value in roles_form.fields.roles.choices %}
<option value="{{ index }}">{{ value }}</option>
{% endfor %}
</select>
<span class="role-error hidden" style="color: red"></span>
</div>
<div class="form-group">
<label for="github_profile">GitHub Profile (optional)</label>
<input type="url" class="form-control" name="github_profile" id="github_profile" placeholder="https://github.com/your-profile">
<span class="github_profile-error hidden" style="color: red"></span>
</div>
我知道这是一个有条件的事情,但是我在Django是一个全新的人,我不太确定如何实现它。
编辑:
我执行了以下函数:
$('select').on('change', function() {
var value = $(this).val();
if (value == 1) {
$('#github_link').show();
} else if (value != 1) {
$('#github_link').hide();
}
})
它可以工作,但我得到了以下反馈:这里你已经硬编码了值"1",但是如果这个列表上的位置改变了,那么这个行为就会崩溃。相反,您应该引用变量{{ model.profile.DEVELOPER }},该变量将生成变量DEVELOPER的当前值,即使它发生了变化。
发布于 2018-06-08 01:45:27
我认为实现这个目标的唯一方法是使用Javascript。例如,使用如下示例中的jQuery:https://stackoverflow.com/a/26589859/5698557
https://stackoverflow.com/questions/50746932
复制相似问题