首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django,从数据库中使用样式

Django,从数据库中使用样式
EN

Stack Overflow用户
提问于 2018-08-30 13:35:11
回答 2查看 854关注 0票数 0

在我的数据库中是样式,我想在模板中使用它,但我不知道如何使用。

models.py

代码语言:javascript
运行
复制
class Post(models.Model):
    # ...

    body = models.TextField()  # HTML
    style = models.TextField()  # CSS

    # ...

views.py (我不知道它是否有用)

代码语言:javascript
运行
复制
# ...
# 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)

# ...

我试过:

代码语言:javascript
运行
复制
{# ... #}

<style>
    {{ post.style }}
</style>

{# ... #}

(我知道如何使用保存在“静态”目录中的样式)

我使用django 2.1和python 3.7。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-30 18:08:23

它并不是那么复杂,但它需要一些步骤。你需要:

  1. 创建2个新文件(例如styling.py、post.css)
  2. 编辑您的模型
  3. 编辑基本模板

styling.py

代码语言:javascript
运行
复制
from django.template.loader import render_to_string


def get_style(post):
     return render_to_string('post.css', {'post': post})

post.css

代码语言:javascript
运行
复制
{% if post.style %}
    {{ post.style }}
{% endif %}

或者,如果您只想在样式字段中存储一个值,例如background-color

代码语言:javascript
运行
复制
{% if post.style %}
    background-color: {{ post.style }}
{% endif %}

在你的model.py里

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
<html>
<head>
    {% if post %}
    <style>
    {{ post.get_style_sheet()|safe }}
    </style>
    {% endif %}
</head>
票数 0
EN

Stack Overflow用户

发布于 2020-08-19 08:12:18

代码语言:javascript
运行
复制
   <html>
    <head>
        <style>
        {{ variable_name|safe }}
        </style>
    </head>

其中variable_name是包含css的变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52098427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档