带有“parser.compile_filter(tokens[2])”的 Django 自定义模板标签;不起作用

发布于 2024-08-31 02:27:28 字数 2117 浏览 1 评论 0原文

我尝试实施 T. Stone 针对我的问题“how-do-i-pass-a-lot-of-parameters-to-views-in-django”提出的解决方案([链接文本][1])。< br> 我无法得到任何结果。很难找到有关 compile_filter() 的信息,但据我了解 cls(queryset=parser.compile_filter(tokens[2]), template=template) 应该使用“变量”标记渲染模板[2]。但这似乎不起作用。

这是我的实现代码:
models.py:views.py:mytags.py:test.html:testtable.html

class SalesRecord(models.Model):
    name = models.CharField(max_length=100)
    month = models.CharField(max_length=10)
    revenue = models.IntegerField()
    def __unicode__(self):
        return self.name + " - " + self.month + " - " + str(self.revenue)

def test(request, *args, **kwargs):
    name = 'John'
    monthly_sales_qs = SalesRecord.objects.filter(name=name)
    print monthly_sales_qs
    return render_to_response('test.html', locals())

class DataForTag(template.Node):
    @classmethod
    def handle_token(cls, parser, token, template):
        tokens = token.contents.split()
        if tokens[1] != 'for':
                raise template.TemplateSyntaxError("First argument in %r must be 'for'" % tokens[0])

        if len(tokens) == 3:
            return cls(queryset=parser.compile_filter(tokens[2]), template=template)
        else:
            raise template.TemplateSyntaxError("%r tag requires 2 arguments" % tokens[0])

    def __init__(self, queryset=None, template=None):
        self.queryset = queryset
        self.template = template

    def render(self, context):
        return render_to_string(self.template, {'queryset':self.queryset})

@register.tag
def render_data_table(parser, token):
    return DataForTag.handle_token(parser, token, 'testtable.html')

页面

{% load mytags %}
{% render_data_table for monthly_sales_qs %}

:

<table class="tabledata">
    <tr>
    {% for m in queryset.month %}
        <td>queryset.revenue</td>
     {% endfor %}
     </tr>
</table>

模板仅返回一个 在我看来,查询集是空的。 有人知道我做错了什么吗? (可能是一些初学者的愚蠢;)

I tried to implement the solution proposed by T. Stone on my question "how-do-i-pass-a-lot-of-parameters-to-views-in-django" ([link text][1]).
I can't manage to get any result. It's difficult to find information about the compile_filter(), but as far as I understand cls(queryset=parser.compile_filter(tokens[2]), template=template) should render the template with the 'variable' tokens[2]. But that doesn't seems to work.

Here is the code of my implementation:
models.py:

class SalesRecord(models.Model):
    name = models.CharField(max_length=100)
    month = models.CharField(max_length=10)
    revenue = models.IntegerField()
    def __unicode__(self):
        return self.name + " - " + self.month + " - " + str(self.revenue)

views.py:

def test(request, *args, **kwargs):
    name = 'John'
    monthly_sales_qs = SalesRecord.objects.filter(name=name)
    print monthly_sales_qs
    return render_to_response('test.html', locals())

mytags.py:

class DataForTag(template.Node):
    @classmethod
    def handle_token(cls, parser, token, template):
        tokens = token.contents.split()
        if tokens[1] != 'for':
                raise template.TemplateSyntaxError("First argument in %r must be 'for'" % tokens[0])

        if len(tokens) == 3:
            return cls(queryset=parser.compile_filter(tokens[2]), template=template)
        else:
            raise template.TemplateSyntaxError("%r tag requires 2 arguments" % tokens[0])

    def __init__(self, queryset=None, template=None):
        self.queryset = queryset
        self.template = template

    def render(self, context):
        return render_to_string(self.template, {'queryset':self.queryset})

@register.tag
def render_data_table(parser, token):
    return DataForTag.handle_token(parser, token, 'testtable.html')

test.html:

{% load mytags %}
{% render_data_table for monthly_sales_qs %}

testtable.html:

<table class="tabledata">
    <tr>
    {% for m in queryset.month %}
        <td>queryset.revenue</td>
     {% endfor %}
     </tr>
</table>

The template just returns an empty page. It seems to me that the queryset is empty.
Does someone have an idea what I'm doing wrong? (probably some beginners stupidity ;)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故人的歌 2024-09-07 02:27:28

马克……

有几件事:有一天,当我为你发布该代码时,我很着急。在 render 方法中,变量需要这样解析...

def render(self, context):
    qs = self.queryset.resolve(context)
    return render_to_string(self.template, { 'queryset': qs } )

另外,在您的模板中,这是错误的:

{% for m in queryset.month %}
    <td>queryset.revenue</td>
 {% endfor %}

首先,变量需要包装在 {{ }} 中,例如 { { queryset.revenue }} 其次,您没有对 m 值执行任何操作,因此使用 for 循环是没有意义的。

最后,我在 django.contrib.comments 应用程序中找到的答案中向您展示了模式。如果您想遵循一些现有/工作示例,我建议您查看评论模板标签。该应用程序中有很多很棒的想法。

Mark...

Couple of things: I was in a rush the other day when I posted that code for you. Within the render method variables need to be resolved as such...

def render(self, context):
    qs = self.queryset.resolve(context)
    return render_to_string(self.template, { 'queryset': qs } )

Also, in your template, this is wrong:

{% for m in queryset.month %}
    <td>queryset.revenue</td>
 {% endfor %}

First, variables need to be wrapped in {{ }}'s like {{ queryset.revenue }} and second you're not doing anything with the m value so having the for loop is pointless.

Lastly, the pattern I showed you in the answer I found in the django.contrib.comments app. If you want to follow some existing/working examples I'd recommend checking out the comments template tags. Lots of great ideas in that app.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文