【问题标题】:How to get a model by modelname in django template如何在 django 模板中通过模型名获取模型
【发布时间】:2019-01-14 01:04:25
【问题描述】:

我的模型 LandingSnippet 包含属性...model = CharField()...,它与上下文关键字相关(例如下面context 中的cars

我的视图中有下一个代码

def GeneratedLanding(request):
    snippets = LandingSnippet.objects.all().filter(view_on=True).order_by('order')

    context = {
        'snippets':snippets,
        ...
        'cars':Car.objects.all(), # this is cars
        ...
    return render(request,'qlanding/generateindex.html',{'context':context})

我如何通过关键字cars 将上下文中的querySet cars 作为字符串获取

例如

{{context}}

打印

{'snippets': <QuerySet [<LandingSnippet: Snippet1Title>, <LandingSnippet: 2 - about - Лучшая служба развозки детей>]>, 'services': <QuerySet []>, 'cars': <QuerySet []>, 'faqs': <QuerySet []>}

{{snippet.model}}

打印

cars

问题: 我怎样才能得到{{ context.cars }} ?我想像context[snippet.model] where sn-p.model='cars'

我想在包含时将其推送到另一个模板中

{% if snippet.module %}
  {% with "qlanding/snippets/module/"|add:snippet.module|add:".html" as path %}
  {% include path with model=context[snippet.model] %} # But this is incorect while rendering
  {% endwith %}
{% endif %}

【问题讨论】:

  • 我可以看看你的模型吗?
  • 返回渲染(request,'qlanding/generateindex.html',context)
  • @MohammadAli 这里是我的模型文件dropmefiles.com/l1dFv

标签: django django-templates django-template-filters


【解决方案1】:

@vorujack ,我仍然遇到同样的错误。但根据您的解决方案,我得到了下一个。

  from Django import template
  register = template.Library()
  @register.simple_tag
  def get_model_from_context(context,model_name):
      return context[model_name]

以及我在视图中的使用方式

 {% get_model_from_context context=context model_name=snippet.model as model %}
 {% include "qlanding/snippets/module/"|add:snippet.module|add:".html" with model=model %}

非常感谢@vorujack

【讨论】:

    【解决方案2】:

    你可以这样写一个简单的模板标签:

    首先在你的应用目录中创建一个名为templatetags的目录,该目录必须包含一个名为__init__.py的空文件

    在此目录中创建一个任意名称的文件。例如load_from_context

    在这个文件上写下这些代码

    from django import template
    
    register = template.Library()
    
    
    @register.tag(name="GetFromContext")
    def get_from_context(parser, token):
        bits = token.split_contents()
        node_list = parser.parse(('endGetFromContext',))
        variable = bits[1]
        return GetFromContextNode(node_list, variable)
    
    
    class GetFromContextNode(template.Node):
    
        def __init__(self, node_list, variable):
            self.node_list = node_list
            self.variable = variable
    
        def render(self, context):
            variable_value = template.Variable(self.variable).resolve(context)
            with context.push():
                context['model'] = context.get(variable_value)
                return self.node_list.render(context)
    

    然后在你的模板中你可以像这样使用它

    {% load load_from_context %}
    
    {# any code in your template #}
    
    {% GetFromContext snippet.model %}
        {% include path %}
    {% endGetFromContext %}
    

    【讨论】:

    • 嗨,我收到错误“load_from_context”不是已注册的标签库。必须是以下之一: admin_list admin_modify admin_static admin_urls cache fontawesome i18n l10n log static staticfiles tinymce_tags tz
    • 我刚刚重做了所有步骤,关闭了服务器
    • 更改了第一行:from django import template 实际问题是 endGetFromContext 未注册。
    • 你说得对。它是一个打字错误。将行 node_list = parser.parse('endGetFromContext') 更改为 node_list = parser.parse(('endGetFromContext'),)。我更新答案
    • 嗨,我从有关括号的文档中找到并尝试过。但我收到错误Invalid block tag on line 24: 'endGetFromContext', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
    猜你喜欢
    • 2018-03-10
    • 2011-07-04
    • 2017-09-14
    • 2016-04-14
    • 2016-08-04
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多