访问Django模板中的字典值

2024-05-14 20:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮助我在django模板中显示dictionary的值。我试着用谷歌去寻找答案,但没能找到解决方案。在

下面是模型

class Ride(models.Model): 
    type = models.BooleanField(default=False)
    add_source = models.ForeignKey(Address, related_name='source')
    add_destination = models.ForeignKey(Address, related_name='destination')
    ride_comment = models.TextField(null=True,max_length=140,blank=True)
    def __unicode__(self):
        return self.ride_comment

class Driver(models.Model):
    ride_id = models.ForeignKey(Ride)
    user_id = models.ForeignKey(User)
    drv_carseats = models.SmallIntegerField(null=True,blank=False)
    def __unicode__(self):
        return self.user_id.username

视图

^{pr2}$

这是我的模板代码

{% for result in result_list %}
     {% if result %}
         <a href="/rides/ridedetails/{{ result.pk }}">{{ userList[result.pk] }}</a>
         <em>{{ result.add_source }}</em>
         <em>{{ result.add_destination }}</em>
         <em>{{ result.ride_comment }}</em>
     {% endif %}
{% endfor %}

我得到以下错误

TemplateSyntaxError at /rides/search/

Could not parse the remainder: '[result.pk]' from 'userList[result.pk]'


Tags: selfadd模板idtruesourcemodelscomment
2条回答

您不需要创建字典来访问模板级别的驱动程序,您可以follow the relationship backward,因为Driver模型具有Ride模型的外键:

{% for result in result_list %}
     {% if result %}
         {% with result.driver_set.all as drivers %}
             {% for driver in drivers %}
                 <a href="/rides/ridedetails/{{ result.pk }}">{{ driver.user_id }}</a>
             {% endfor %}
         {% endwith %}
         <em>{{ result.add_source }}</em>
         <em>{{ result.add_destination }}</em>
         <em>{{ result.ride_comment }}</em>
     {% endif %}
{% endfor %}

ForeignKey指定related_name是很好的做法,因为这样可以更方便地访问对象:

^{pr2}$

然后您可以:

ride = Ride.objects.get(id='some_id')
drivers = ride.drivers.all()

您应该为此编写一个django自定义过滤器。在

创建一个文件名get-tu dict_值py在你的应用程序内。。在

project
   -app
      -templatetags
          __init__.py
          get_dict_val.py

现在就要开始了_值py在

^{pr2}$

在模板中 将此添加为第一行写入。。在

{% load get_dict_val %}

现在在模板中替换代码

<a href="/rides/ridedetails/{{ result.pk }}">{{ userList|get_item:result.pk }}</a>

相关问题 更多 >

    热门问题