【发布时间】:2021-06-02 12:07:58
【问题描述】:
我正在处理的网站正在使用一个模型来发布帖子,并使用另一个链接模型来制作将附加到帖子的图像。
page_choices = {
('news', 'news'),
('activities', 'activities'),
('environment', 'environment'),
('affairs', 'affairs'),
('links', 'links'),
}
link_choices = {
('external', 'external'),
('none', 'none'),
('pdf', 'pdf'),
('image', 'image'),
}
class Post(models.Model):
id = models.AutoField(primary_key=True)
page = models.CharField(
choices=page_choices,
max_length=11,
default='news',
)
title = models.CharField(null=True, max_length = 100)
content = models.CharField(null=True, max_length = 10000)
image_filename = models.ForeignKey('Image', on_delete=models.DO_NOTHING, null=True, blank=True)
has_image = models.BooleanField(default=False)
class Image(models.Model):
id = models.AutoField(primary_key=True)
image_file = models.ImageField()
name = models.CharField(null=True, max_length = 100)
identifier = models.CharField(null=True, max_length = 100)
alt_text = models.CharField(null=True, max_length = 100)
link_address = models.CharField(null=True, blank=True, max_length = 100, help_text="Optional")
link = models.CharField(
choices=link_choices,
max_length=8,
default='none',
)
这些模型由视图呈现给 HTML,我正在尝试添加 JS/jQuery 以向图像添加链接功能。我正在尝试获取指向单击图像时应呈现的 pdf 的静态目录的链接。
{% if post.image_filename.link == "pdf" %}
<script>
$(document).ready(function() {
$("#{{post.image_filename.identifier}}").click(function() {
location.href = "{% static 'images/{{ post.image_filename.link_address }}' %}";
});
});
</script>
{% endif %}
将 {{ }} 放在模板标签 {% %} 内不起作用,我尝试使用 {% with post.image_filename.link_address as link_address %},但在这种情况下我也无法让它工作:
$("#{{post.image_filename.identifier}}").click(function() {
location.href = "{% static 'images/post.image_filename.link_address' %}";
});
TemplateSyntaxError 'with' received an invalid token: 'post.image_filename.image_file'
任何指导将不胜感激,谢谢。
【问题讨论】:
标签: javascript jquery django django-templates