如何在Django模板内对PostgreSQL JSON字段元素进行if语句处理

huangapple go评论62阅读模式
英文:

How to make if statements on postgresql json field elements inside a django template

问题

在 Django 模板语言中,你的拼写可能有点问题。请检查你的条件语句中的单词 "setttings",看起来应该是 "settings"。

英文:

I am having a hard time checking if a json field contains certain variable value in django template language.

This is my model:

from django.db.models import JSONField

class Widget(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    endpoint = models.CharField(max_length=512)  # "/data/id"
    type = models.CharField(max_length=64, default="line-graph")
    settings = JSONField(default=dict)

This is how I insert data to this model:

widget, created = Widget.objects.get_or_create(
    user=request.user,
    endpoint=endpoint,
)
widget.type = type_
widget.settings = {
    "code": "",
    "dashboard": dashboard.id,
    "position": "top",
    "params": "per=m&len=1"
}

However, when I do this in the template it fails:

{% if widget.setttings.position == "top" %}

This does not fail, on the other hand:

{% with widget.settings.position as pos %}
    {% if pos == "top" %}

and by "fail" I mean it doesn't pass the condition.

Am I doing something wrong?

  • Django version: 3.2
  • Python version: 3.8
  • PostgreSQL version: 12.10

答案1

得分: 2

你这里有3个't':

{% if widget.setttings.position == "top" %}
英文:

You have 3x 't' here:

{% if widget.setttings.position == "top" %}

huangapple
  • 本文由 发表于 2023年4月11日 03:14:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定