【问题标题】:How access a context value from a variable in django template如何从 django 模板中的变量访问上下文值
【发布时间】:2017-12-08 17:32:37
【问题描述】:

我有一个问题模型,我将其作为上下文传递给模板

class Question(models.Model):
    possible_answer1 = models.TextField(
        'Possible Answer 1',
        max_length=1000,
        default='none'
    )
    possible_answer2 = models.TextField(
        'Possible Answer 2',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer3 = models.TextField(
        'Possible Answer 3',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer4 = models.TextField(
        'Possible Answer 4',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer5 = models.TextField(
        'Possible Answer 5',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer6 = models.TextField(
        'Possible Answer 6',
        max_length=1000,
        default='none',
        blank=True
    )

如果我使用,我可以访问所有答案对象没有问题

{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
.
.
{{ context.this_question.question.possible_answer6 }}

问题是我不需要一直显示所有 6 个答案,所以我试图构建 for 循环,该循环只会根据以下线程使用 with 标签 @ 在特定时间显示我需要的内容987654321@1。在下面的示例中,mylist 包含四个元素,所以我尝试了这个

{% for x in mylist %}
    {% with possible_answer='context.this_question.question.possible_answer'|add:forloop.counter %}
      {{ possible_answer }}
    {% endwith %}
{% endfor %}

希望它会产生

{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
{{ context.this_question.question.possible_answer3 }}
{{ context.this_question.question.possible_answer4 }}

并因此显示上下文对象中的相应项目,就好像我自己键入它一样,但它不起作用。什么都没有显示

如果将 forloop.counter 替换为任何字符串,它将显示连接的字符串,而不会尝试在上下文中获取值。

有人知道如何实现这一目标吗?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    这种逻辑最好在视图中生成。您可能还需要重新考虑您的数据库架构。当我遇到这类问题时,我最好创建两个不同的模型。

    例如一个 Question 模型和一个 Answer 模型。 Answer 模型将具有 Question 模型的外键,然后使用简单的过滤器获取与该问题相关的所有答案。它是一种简单的 SQL 数据库编程范式。

    models.py

    class Question(models.Model):
      Body = models.TextField(max_length=1000,default='none',blank=True)
    
    class Answer(models.Model):
      Question = models.ForeignKey(Question)
      Body = models.TextField(max_length=1000,default='none',blank=True)
    

    views.py:

    Q = Question.objects.get(pk='id')
    A = Answer.objects.filter(Question=Q)
    

    希望对你有帮助!

    【讨论】:

    • 没想过将问题和答案分开。会考虑的谢谢。我仍然想知道我想要实现的目标是否可以直接从模板中实现。
    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2019-11-10
    • 2017-02-12
    • 2013-09-15
    • 2019-12-05
    相关资源
    最近更新 更多