[英]Is there a way to pass URL template tag from database to template in Django?
如果我的問題措辭不當,我深表歉意。 基本上,我正在制作一個虛構角色的數據庫,並且在數據庫中,我有一個角色的傳記。 我想使用{% url 'viewname' otherchar.slug %}
方法鏈接到其他字符。 但是,我從數據庫中得到的只是那行代碼。
我知道這可能是不可能的,但是有沒有辦法讓 Django 看到那條線並將其變成絕對的 URL 就像我手動將 ZE6B391A8D2C4D459702A23A8B6585 標簽添加到頁面中一樣?
Something to add - I am using TinyMCE so the content in the database is being saved with HTML - I want to be able to save external links, subheadings, and whatnot, which is why I chose to use TinyMCE and its HTML field.
模型.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()
視圖.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
網址.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...
我很感激你們可以提供的任何幫助。 我似乎在這里或谷歌上找不到任何東西。 謝謝!
您可以將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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.