在我的数据库中是样式,我想在模板中使用它,但我不知道如何使用。
models.py
class Post(models.Model):
# ...
body = models.TextField() # HTML
style = models.TextField() # CSS
# ...views.py (我不知道它是否有用)
# ...
# Context have to be get to every template extends form 'base.html'
base_context = {
"category": Category.objects.all(),
}
# ...
def detail(request, slug, day, month, year):
context = base_context.copy()
context['post'] = Post.objects.get(slug=slug,
created__day=day,
created__month=month,
created__year=year)
return render(request, 'post/detail.html', context)
# ...我试过:
{# ... #}
<style>
{{ post.style }}
</style>
{# ... #}(我知道如何使用保存在“静态”目录中的样式)
我使用django 2.1和python 3.7。
发布于 2018-08-30 18:08:23
它并不是那么复杂,但它需要一些步骤。你需要:
styling.py
from django.template.loader import render_to_string
def get_style(post):
return render_to_string('post.css', {'post': post})post.css
{% if post.style %}
{{ post.style }}
{% endif %}或者,如果您只想在样式字段中存储一个值,例如background-color
{% if post.style %}
background-color: {{ post.style }}
{% endif %}在你的model.py里
from styling import get_style
class Post(models.Model):
...
style = models.TextField() # CSS
....
def get_style_sheet(slef):
return get_style(self)在基本模板中添加以下内容,但要确保上下文中有post对象
base.html
<html>
<head>
{% if post %}
<style>
{{ post.get_style_sheet()|safe }}
</style>
{% endif %}
</head>发布于 2020-08-19 08:12:18
<html>
<head>
<style>
{{ variable_name|safe }}
</style>
</head>其中variable_name是包含css的变量。
https://stackoverflow.com/questions/52098427
复制相似问题