【问题标题】:Is there a way to pass URL template tag from database to template in Django?有没有办法将 URL 模板标签从数据库传递到 Django 中的模板?
【发布时间】:2021-06-04 19:10:49
【问题描述】:

如果我的问题措辞不当,我深表歉意。基本上,我正在制作一个虚构角色的数据库,并且在数据库中,我有一个角色的传记。我想使用{% url 'viewname' otherchar.slug %} 方法链接到其他字符。然而,我从数据库中得到的只是那一行代码。

我知道这可能是不可能的,但有没有办法让 Django 看到该行并将其转换为绝对 URL,就像我手动将 URL 标记添加到页面中一样?

要添加的东西 - 我正在使用 TinyMCE,因此数据库中的内容使用 HTML 保存 - 我希望能够保存外部链接、副标题和诸如此类的东西,这就是我选择使用 TinyMCE 及其 HTML 字段的原因.

models.py

class Character(models.Model):
    name = models.CharField(max_length = 255)
    faction = models.IntegerField(default = 0)
    rankIMG = models.ImageField(upload_to = 'rankIMG/', blank = True)
    department = models.IntegerField(default = 0)
    content = HTMLField()
    slug = models.SlugField()

views.py


class CharacterFull(DetailView):
    model = Character
    context_object_name = 'character'

    def get_context_data(self, **kwargs):
        context = super(CharacterFull, self).get_context_data(**kwargs)
        context['factionDict'] = charFaction
        context['deptDict'] = charDepartment

        return context

urls.py

app_name = 'LCARS'

urlpatterns = [
    path('', LCARSView.LCARSHome.as_view(), name = 'lcarsHome'),
    path('Characters/', LCARSView.Characters.as_view(), name = 'characterHome'),
    path('Characters/p/<slug:slug>', LCARSView.CharacterPartialView, name = 'charPartialView'),
    path('Characters/<slug:slug>/', LCARSView.CharacterFull.as_view(), name = 'characterView'),
]

模板(相关代码)

<div class="col-md-8 p-4 text-justify border border-secondary rounded shadow">
    {{ character.content|safe }}
</div>

页面来源示例(如果有帮助)

<p dir="ltr">He was also assigned <a href="{% url 'LCARS:characterView' character.slug %}">Commander Shampoo</a> as his...

感谢你们提供的任何帮助。我似乎在这里或谷歌上找不到任何东西。谢谢!

【问题讨论】:

  • 我稍作修改以添加我的 urls.py 文件,以防万一也有帮助。

标签: python html django django-models django-templates


【解决方案1】:

您可以将get_context_data中的内容渲染为模板:

from django.template import Template, RequestContext

class CharacterFull(DetailView):
    model = Character
    context_object_name = 'character'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['factionDict'] = charFaction
        context['deptDict'] = charDepartment
        self.object.other_attribute = Template(
            self.object.content
        ).render(RequestContext(self.request, context))
        return context

其中.other_attribute 是您用作字段、属性、方法等的标识符。

然后在“外部”模板中渲染它:

<div class="col-md-8 p-4 text-justify border border-secondary rounded shadow">
    {{ character.other_attribute|safe }}
</div>

【讨论】:

  • 你这个很棒的人,效果很好。谢谢你。因此,该解决方案基本上是从数据库中预渲染“内容”字段,以便在将 Jina 标签实际渲染到模板中进行显示之前对其进行处理?
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 2021-02-15
  • 1970-01-01
  • 2017-08-11
  • 2015-02-02
  • 1970-01-01
  • 2021-05-12
  • 2016-08-26
相关资源
最近更新 更多