【问题标题】:Can you add html meta-description to django blog post model?您可以将 html 元描述添加到 django 博客文章模型吗?
【发布时间】:2021-04-05 16:33:51
【问题描述】:

我想知道是否有可能/google 允许将 meta_description CharField 添加到 Post 模型以动态更改 html 页面上的元描述?

我当前的元描述是

<meta name="description" content="{{ post.title }} blog post from the {{ post.category }} category.">  

这显然并不理想,因为它没有很好地描述单个博客文章。然后我开始考虑是否可以在同一个庄园中添加一个字段设置。这样我就可以将 CharField 设置为最大长度,这样我就知道所有元描述都是适当的长度,并且我可以为每篇博文设置适当的描述。

class Post(models.Model):
   title = models.CharField(max_length =250)
   body = RichTextField(blank=True, null=True)
   meta_description = models.CharField(max_length=150)


<meta name="description" content="{{ post.meta_description }}"
  • 在我尝试实施之前,是否有人发现这有任何问题?
  • 有人知道 Google 是否允许这样做吗?

【问题讨论】:

    标签: html django django-models meta-tags


    【解决方案1】:

    您可以使用 blocks 而不是专门为此创建新的 meta description 字段,并且 Google 允许这样做...

    在您的 base.html 中:

    <head>
         ...
         ...
        {% block metadescription %}
            <meta name="description" content="This site provide something...">
        {% endblock %}
    
    </head>
    

    还有你的post_detail.html

    {% extends "../base.html" %}
    
    {% block metadescription %}
        <meta name="description" content="{{post.description|truncatechars:25}}">
    {% endblock %}
    
    {% block content %}
       ....
    {% endblock %}
    

    更新以下评论的答案:

    在这里您可以使用property 类并在context 中传递此属性..

    models.py

    class Post(models.Model):
       title = models.CharField(max_length =250)
       body = RichTextField(blank=True, null=True)
    
        @property
        def convert_in_meta(self):
            title = (self.title)[0:50]
            body = (self.body)[0:100]
            description = title + str(body)
            return description
    

    views.py:

    def post_detail(request,pk):
        post = Post.objects.get(id = pk)
        post_meta = post.convert_in_meta
        return render(request,"post_detail.html",{'post_meta':post_meta,...})
    

    【讨论】:

    • 我已经为网站的其余部分和当前帖子使用了块,如原始帖子所示,我目前正在使用 post.title 和 post.category 来制作元描述。我没有每个帖子的字段描述,只有标题、正文、类别和标签。我想我可以尝试使用 body 并截断字符,并尝试确保每篇博文都有一个描述性的前 150 个字符,但我认为创建一个新字段并使用它可能更容易。您认为最好的解决方案是什么?
    • @LBJ33 使用property 类并在context 中传递它,而不是为此创建新字段...请参阅上面我更新的answer
    猜你喜欢
    • 2023-02-18
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2012-02-24
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多