Django 中添加元关键字

在 Django 项目中,需要在模板中添加元关键字(meta keywords),但使用以下代码却未能成功:
在这里插入图片描述

@template_render("mysite/category.html")
def category(request, slug):
    slug = slug.lower()
    product_type = local_settings.CATEGORY_NAME_TO_ID.get(slug, False)
    if not product_type:
        raise Http404
    products = models.Product.objects.active().filter(product_type = product_type).all()
    return { 'products' : products, 'slug' : slug, 'key':'wholesale ipad, ipad with retina display, ipad mini, ipad 3, ipad 2',}

在模板文件中,使用以下代码:

{% extends "base.html"%}
{%load appletrade_tags%}
{% block key %}siteTrade - {{key}}{% endblock %}
{%block title%}site Trade - {{slug}}{%endblock%}

在查看页面源代码时,发现并没有添加元关键字,但标题却可以正常显示。

2、解决方案

方法一:使用 render_to_response 函数

在视图函数中,使用 render_to_response 函数来传递上下文数据给模板,如下所示:

from django.shortcuts import render_to_response

def category(request, slug):
    slug = slug.lower()
    product_type = local_settings.CATEGORY_NAME_TO_ID.get(slug, False)
    if not product_type:
        raise Http404
    products = models.Product.objects.active().filter(product_type = product_type)
    context = {
        'slug': slug,
        'products': products,
        'key': 'wholesale ipad, ipad with retina display, ipad mini, ipad 3, ipad 2',
    }
    return render_to_response('appletrade/category.html', context, context_instance=RequestContext(request))

方法二:使用自动生成元关键字的函数

为了方便地为页面生成元关键字,可以编写一个函数来从模板文件中提取关键词,并返回关键词列表,如下所示:

# meta_gen.py
# create meta keywords for webpage automagically
# MIT License
# Author: Daniel P. Clark 6ftdan@gmail.com
import collections, string, StringIO, re
from django.utils.html import strip_tags

# Counts words in template files and insert keywords into page
word_count_min = 2
word_length_min = 4

nogo_list = [] # Optional list of words you may not want as meta tags.

# meta_keywords ( html string ) => 
#   returns non html keyword list, as a comma seperated string,
#   for words fitting qualifications as chosen above.
def meta_keywords(str_file):
    c = collections.Counter()
    strIO_Obj = StringIO.StringIO(str_file)
    for line in strIO_Obj.readlines():
        c.update(re.findall(r"[\w']+", strip_tags(line).lower()))
    wordlist = []
    for word, count in c.most_common():
        if len(word) > (word_length_min-1) and count > (word_count_min-1) and word not in nogo_list: wordlist.append(word)
    return string.join(wordlist, ',')

在每个视图函数中,添加以下代码:

from project.meta_gen import meta_keywords

this_template = "apptemplate.html"

def tabs(request):
    return render_to_response(this_template, { 'title' : "Page Name", 'keys' : meta_keywords(render_to_string(this_template)) })

在主模板 base.html 中,添加以下代码:

<head>
<title>Site Name - {{ title }}</title>
<meta name="keywords" content="{{ keys }}" />
</head>

这样,就可以自动为每个页面生成并添加元关键字了。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Django项目实现搜索可以通过以下步骤: 1. 定义模型:定义要搜索的模型,例如一个博客模型。 ```python class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() pub_date = models.DateTimeField() ``` 2. 定义视图:定义一个视图用于接收用户的搜索请求,查询数据库,并返回结果。 ```python from django.shortcuts import render from .models import Blog def search(request): query = request.GET.get('q') results = Blog.objects.filter(title__icontains=query) return render(request, 'search.html', {'results': results}) ``` 3. 定义模板:定义一个模板用于展示搜索结果。 ```html {% extends 'base.html' %} {% block content %} <h1>Search Results</h1> {% if results %} <ul> {% for result in results %} <li><a href="{{ result.get_absolute_url }}">{{ result.title }}</a></li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} {% endblock %} ``` 4. 添加搜索表单:在模板添加一个搜索表单,让用户输入搜索关键字。 ```html {% extends 'base.html' %} {% block content %} <h1>Search</h1> <form action="{% url 'search' %}" method="get"> <input type="text" name="q"> <button type="submit">Search</button> </form> {% endblock %} ``` 5. 添加搜索路由:在项目的urls.py文件添加一个搜索路由。 ```python from django.urls import path from .views import search urlpatterns = [ path('search/', search, name='search'), ] ``` 这样就可以在Django项目实现搜索功能了。需要注意的是,以上例子只是一个简单的搜索示例,实际应用可能需要更复杂的搜索功能,例如支持多个关键字、分类搜索等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值