How to add meta keyword with django

2019-05-19 01:37发布

问题:

I am using below code to add meta keywords -

in view.py

@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',}

And in template file -

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

But it's not reflecting. I have checked in view source there is no keyword.

But Yes,title is reflecting.

Can you please help me to find out where I am wrong ?

EDIT :

base.html

{% extends "base.html"%}
{% block key %}{%if page.key%}{{page.key}}{%else%}{{block.super}}{%endif%}{% endblock %}
{% block desc %}{%if page.desc%}{{page.desc}}{%else%}{{block.super}}{%endif%}{% endblock %}
{%block title%}{%if page.title%}{{page.title}}{%else%}{{block.super}}{%endif%}{%endblock%}
{%block content%}
{%endblock%}

回答1:

You need to be using either render or render_to_response to pass a context to the template. Is the slug object appearing on the page?

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))


回答2:

Here is a way to automate keywords for your django site. I don't like manually entering things anyways.

Here's a function to read your template file and count primary words, and return the list of the words used in the page.

# 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, ',')

Place meta_gen.py in your main project folder. Then add these pieces to each of your views.py files.

# views.py
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
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)) })

And lastly in your main template base.html you place the meta tag for keywords.

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

And that's it. All pages that inherit the base template and have the views.py code will insert keywords meta tags with words that repeat on your pages.

I realize that this can be improved upon and optimized. Speed isn't a concern for me. So input is welcome.