【问题标题】:How do I reference a template from a class method in Django?如何从 Django 中的类方法中引用模板?
【发布时间】:2013-04-08 06:08:41
【问题描述】:

是否可以从 Django 中的类方法中引用模板?假设我的模型中有以下课程(用于离线扬声器系列):

class Event(models.Model): 
    name = models.CharField(max_length=300)
    date = models.DateTimeField()
    desc = models.TextField(blank=True, null=True)
    location = models.ForeignKey('Location', blank=True, null=True)
    speaker = models.ForeignKey('Speaker', blank=True, null=True)

我想使用这些属性来填充模板并在 API 帖子中使用生成的 HTML 字符串。如何从这样的类方法中引用 HTML 模板:

def create_event_html(self):
    # This is not working with or without Quotes        
    t = Template(templates/event_template.html) 

    c = Context(self)
    return t.render(c)

在给定特定条件的情况下,我想在保存时调用此类方法,但我认为这与此处无关...

【问题讨论】:

    标签: django django-models django-templates django-views


    【解决方案1】:

    Template(templates/event_template.html) 永远不会工作,因为这根本不是有效的 Python - 它试图将(不存在的)值“模板”除以(也不存在的)对象“事件模板”的“html”属性'。如果你不清楚,你应该做一个 Python 入门教程。

    Template('templates/event_template.html') 是有效的 Python,但会在错误的位置查找模板文件:模板加载器已经在“模板”下查找,因此将在“模板/模板/”中查找“事件模板”。 html'文件。删除目录引用。

    完成后,您将遇到另一个问题,即 Context 需要字典,而您正在传递 self。除非您在模型类上覆盖了 __getitem__,否则这将不起作用。您可能应该只传递一个包含一个条目的字典,例如{'item': self},并且在您的模板中您可以引用item 的各种属性。

    【讨论】:

    • 谢谢,@DanielRoseman - 作为示例,我刚刚删除了不带引号的路径。也许我感到困惑的是 t = Template('event_template.html') 在项目外壳中不起作用。它只是将模板名称解释为一个字符串并返回它 - 这仅仅是因为 settings.py 中的模板目录变量没有被构造,除非你运行服务器?
    • 对不起,我意识到我上面错了。正如您所说,Template('whatever') 从字符串构造模板。您需要使用django.template.loader 中的get_template(location),如here 所述。但总体上使用render_to_string 可能更容易。
    • 啊,完美。确认 render_to_string 完全符合我的需要。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2011-03-31
    • 2018-04-04
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多