英文:
Get item from Django model into HTML
问题
我想在模型models.py
中的每个通知中包含标题和消息。我不想更改我所有的views.py
来实现这一点。我知道可以使用标签{% request.user.name %}
来获取用户的详细信息,但如何在另一个随机模型中实现呢?
我已经尝试了一些方法。以下是我尝试做出更改/创建的文件。
(home
是我的应用程序的名称)
home/templatetags/__init__.py
from .custom_tags import register
home/templatetags/custom_tags.py
from django import template
from home.models import Notifications
register = template.Library()
@register.simple_tag
def notifications():
data = Notifications.objects.all()
return data
home/templates/base.html
{% load custom_tags %}
<html>
<head><!-- 这里有一些代码 --></head>
<body>
<!-- 这里有更多的代码 -->
{% notifications %}
{% for notification in notifications_list %}
{{ notification.title }}
{% endfor %}
</body>
在base.html
中,{% notifications %}
这一行显示为<QuerySet [<Notifications: Notifications object (1)>]>
。但所有其他行都没有显示任何内容。
有人可以告诉我我做错了什么吗?
英文:
I want to include the title and message from every notification in the model Notifications from models.py. I don't want to have to change every single views.py that I have to do this. I know that it's possible to put the tag {% request.user.name %} to get details from the user, but how can I do this with another random model?
I have already tried some things.
These are the files that I created/changed in an attempt to do this.
(home
is the name of my app)
home/templatetags/__init__.py
from .custom_tags import register
home/templatetags/custom_tags.py
from django import template
from home.models import Notifications
register = template.Library()
@register.simple_tag
def notifications():
data = Notifications.objects.all()
return data
home/templates/base.html
{% load custom_tags %}
<html>
<head><!-- Some code here --></head>
<body>
<!-- Some more code here -->
{% notifications %}
{% for notification in notifications_list %}
{{ notification.title }}
{% endfor %}
</body>
In base.html
, the line {% notifications %}
shows <QuerySet [<Notifications: Notifications object (1)>]>
. But all of the other lines don't do anything.
Can anyone tell me what I'm doing wrong?
答案1
得分: 2
一个解决方案是在自定义标签内部呈现html,并使用属于该标签的小型html模板将其返回:
~~~
@register.simple_tag
def notifications():
data = Notifications.objects.all()
context = {"data": data}
return render_to_string("...../notification_tag.html", context)
~~~
然后在base.html中使用:
~~~
<body>
<!-- 这里还有一些其他代码 -->
{% notifications %}
</body>
~~~
英文:
One solution is to render html inside the custom tag with a small html template belonging to the tag and return it:
@register.simple_tag
def notifications():
data = Notifications.objects.all()
context = {"data": data}
return render_to_string("...../notification_tag.html", context)
in the base.html then just use:
<body>
<!-- Some more code here -->
{% notifications %}
</body>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论