Giter VIP home page Giter VIP logo

django-meta's Introduction

django-meta

Join the Gitter chat Latest PyPI version Python versions Latest CI build status Test coverage Code Climate License

Django-Meta is a pluggable Django app that allows developers to easily add meta tags and OpenGraph,
Twitter, and Schema.org properties to their HTML responses.

By adding these tags to their pages, developers can improve the way their pages are displayed in search engine results and on social media platforms.

Warning

INCOMPATIBLE CHANGE: as of version 2.0 django-meta has no longer supports Google+, basic Schema.org support has been introduced.

See https://django-meta.readthedocs.io/en/latest/installation.html

3.2 to 4.2 (newer versions might work but are not tested yet)

Python 3.9 to 3.11

Django-Meta supports a wide range of meta tags, including:

  • Description
  • Keywords
  • Robots
  • Author
  • Google Analytics
  • Open Graph (OG) tags
  • Twitter Cards
  • Schema.org properties

To add meta tags to your pages using Django-Meta, you can use the provided template tags or use the view-method and model-method interface to provide and handle meta information.

django-meta provides a view-method and model-method interface to provide and handle meta informations

For more details check documentation.

By default, Django-Meta is designed to work with HTML responses.

However, it can also be configured to work with non-HTML responses, such as JSON or XML.

To do this, you can define your own meta classes and register them with the django-meta app.

django-meta has been started by Branko Vukelic.

Current maintainer: Iacopo Spalletti

See AUTHORS file for the complete list of contributors

See third_party_apps

Please report all bugs to our Github issue tracker.

django-meta's People

Contributors

asmyshlyaev177 avatar brahim12chamakh avatar cansin avatar dependabot-preview[bot] avatar dmitryfillo avatar ellmetha avatar h1nk avatar joesolly avatar kencochrane avatar leifdenby avatar miratcan avatar mireq avatar peleccom avatar petermorrowdev avatar pre-commit-ci[bot] avatar protoroto avatar therefromhere avatar thesayfulla avatar thijstriemstra avatar timgates42 avatar yakky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-meta's Issues

Base title + base description

class MetadataMixin(object):

    def get_meta_title(self, context=None):
        self.title = getattr(settings, 'META_BASE_TITLE', '') + ' ' + self.title
        return self.title

or

class Meta(object):
 
    def __init__(self, **kwargs):
       self.title = settings.META_BASE_TITLE + ' ' + str(self.title) \
            if getattr(settings, 'META_BASE_TITLE', False) else str(self.title)
        self.description = settings.META_BASE_DESCRIPTION + ' ' + str(self.description) \
            if getattr(settings, 'META_BASE_DESCRIPTION', False) else str(self.description)

BASE_TITLE may be site name or something else, for example

Translations + META isues

Hi. Not sure if it's a 'meta' issue, but it certainly breaks the app at this point.

Create the object.

meta = Meta(
    title=_('Andrey'),
)

Pass it into template context. Raises the error: UnicodeDecodeError at / 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

# Error during template rendering
{% if meta.title %}{% og_prop 'title' meta.title %}{% endif %}

Thanks ahead.

META_TWITTER_TYPE settings not working in MetadataMixin

I'm using MetadataMixin in my views and was unable to add the twitter:card globally using settings.

In settings documentation there is META_TWITTER_TYPE that work great with ModelMeta by adding twitter_type in context.

In MetadataMixin twitter_type is not added in context, instead twitter_card is set. But twitter_card value could only be set in views not in settings.

Should it be best to:

  1. Add another META_TWITTER_CARD settings and read this as default value in MetadataMixin
  2. Normalise the twitter_type and twitter_card in ModelMeta and MetadataMixin to use only one term

I'll make a PR with solution 1. If solution 2 looks better for you, let me know and i'll try to do it.

meta.views.Meta ignores some keys

Hi guys,
when I pass my seo metadata to meta.views.Meta.__init__ function, some keys are ignored because the __init__ function get from **kwargs only what it needs.

So if I pass my Meta object to the template, I cannot find these attributes used by the template meta/meta.html:

  • og_author_url
  • og_author
  • og_publisher
  • og_profile_id
  • tag

It seems that the same happens if I use a DjangoModel that inherits from meta.ModelMeta and I pass to the context my DjangoModel().as_meta() object

What am I doing wrong?

p.s.
I'm using django-meta==1.4.1

Thanks in advance

'ImageFieldFile' object has no attribute 'startswith'

I'm trying to add the tags to a website, but it's showing this error and I don't know what to do.

My models.py

class News(ModelMeta, models.Model):
    title = models.CharField(max_length=200)
    content= RichTextUploadingField()
    date = models.DateTimeField('published_date')
    image = models.ImageField(upload_to="images", blank=False)
    category = models.ForeignKey(
        Category, default=1, verbose_name="Categories",
        on_delete=models.SET_DEFAULT)
    post_slug = AutoSlugField(populate_from='title')

    _metadata = {
        'title': 'title',
        'image': 'image',
    }

    def get_meta_image(self):
        if self.image:
            return self.image.url

    def __str__(self):
        return self.title

I'm using Python 3.8 and Django 3.1.2

Traceback:

File "/home/kamurichanalt/.virtualenvs/tvsite-virtualenv/lib/python3.8/site-packages/meta/views.py", line 125, in image
if not image.startswith('http') and not image.startswith('/'):

Exception Type: AttributeError at /cookie-day
Exception Value: 'ImageFieldFile' object has no attribute 'startswith'

Thanks.

keyword is not rendering properly.

I'm trying to use django-meta in my project but, keyword is not rendering properly. here is screnshot.
Screenshot from 2020-07-20 20-03-56
and here is my setup

.................................
    image_credit = models.CharField(_("Image Credit"), max_length=50)
    content = models.TextField(_("Content"))
    keyword = models.TextField(_("Keyword"), editable=True)
..............................

    class Meta:
        ordering = ['-updated']
        verbose_name = _("Post")
        verbose_name_plural = _("Posts")

    def clean_content(self, *args, **kwargs):
        import re
        cleanr = re.compile('<.*?>')
        cleantext = re.sub(cleanr, '', self.content)
        return cleantext

    _metadata = {
        'title': 'title',
        'description': 'clean_content',
        'image': 'get_meta_image',
        'keywords': 'keyword',
    }

    def get_meta_image(self):
        if self.image:
            return self.image.url

Why not have <title></title> in the meta.html?

I use meta_extended.html which looks like this:

{% include "meta.html" %}
{% if meta.title %}<title>{{ meta.title }}</title>{% endif %}

I suggest add this to the django-meta: title tag is meta/seo tag too. For example, we can add property to the view mixin which enables/disables showing <title></title> in this way:

class MyView(MetadataMixin, View):
    title = 'Some page'
    title_tag = True # enables <title></title> in the meta.html
    description = 'This is an awesome page'
    image = 'img/some_page_thumb.gif'
    url = 'some/page/'

meta.use_facebook AttributeError

I've been trying to incorporate django-meta into a project. However, I running into an issue when putting namespaces into the head tag. Django 1.9 is raising an AttributeError 'dict' object has no attribute 'use_facebook' at line 197 of meta/templatetags/meta.py.

I am having this problem in django-meta 1.2 and 1.3b3. Am I missing something important, or is django-meta failing to set the use_facebook attribute for the Meta class?

The top of my template looks like:
<!DOCTYPE html>
<html>{% load staticfiles %}{% load meta %}
<head lang="en" {% meta_namespaces %}>

In my settings I have:
META_SITE_PROTOCOL = 'http'
META_USE_TITLE_TAG=True
META_SITE_NAME = "Site name"
META_SITE_DOMAIN = 'Site domain'
META_USE_OG_PROPERTIES = True
META_USE_FACEBOOK_PROPERTIES = True

In my view, the context dictionary is:
context_dict['meta'] = {
'use_title_tag':True,
'use_facebook':True,
'title':...
}

Improved / generic schema.org support

We have all the machinery we need for a better schema.org support, and to allow generating metadata in json+ld format

We should definitely make easier and more straightforward to output rich and valid schema.org metadata

Question: Is there a reason meta title and og:title are the same?

I've been recently implementing django-meta into a project and noticed that <title> and <meta property="og:title" /> both use the same exact variable (title) as opposed to description, which has a specific, optional og_description, that falls back to description.

I'm wondering if there's intention behind this (maybe I'm unaware of a best practice?) or if a PR to making it more like the description property would be welcome?

Thanks!

Meta tags escaped in Django 1.9

I am using this package with DJango 1.9 and it seems the meta tags are escaped. Making the below changed in meta.py makes it work fine

@register.simple_tag
def custom_meta(key, name, value):
    return mark_safe('<meta %s="%s" content="%s">' % (escape(key), escape(name), escape(value)))

Can you please check and update ?

Support schema-less urls for images

I hit an issue with django-meta where I was using a schema-less URL for my MEDIA_URL (eg //mycdn/ ).

Django-meta doesn't handle this case correctly (Meta.get_full_url() sees the leading / and treats it as a relative URL, so you end up with http://example.com//mycdn/myimage.jpg instead of http://mycdn/myimage.jpg ).

I think the fix is simple (check for // before / and just add self.get_protocol protocol if // is found), I'll add a pull request to cover this.

`META_DEFAULT_IMAGE`, when specified, ignores `META_IMAGE_URL` when it's empty.

Presumably it should prepend STATIC_URL, but looks like it doesn't. Temporary fix is:

META_DEFAULT_IMAGE = STATIC_URL + 'img/og-image.png'

I see it should be working from code, but:

META_DEFAULT_IMAGE = 'img/og-image.png'

Results win an og:image in meta tags with the URL 'img/og-image.png', for some reason.

Thanks ahead

Defferent keyword for different post

This plugin works great with django 1.11. But adding individual keywords though blog it separates word as character. Here is my models.py

class BlogModel(ModelMeta, models.Model):
    user = models.CharField(max_length=200, blank=True, null=True)
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(unique=True)
    content = models.TextField(blank=True, null=True)
    created = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    keywords = models.CharField(max_length=200, blank=True, null=True)
    

    class Meta:
        verbose_name = 'Blog'

    _metadata = {
        'title': 'title',
        'description': 'content',
        'keywords': 'keywords'
    }

I can not understand how can I update keywords as post specific thought plugin itself.

Immediately what I have done for this:
in the plugins view.py line no 91
kws = [k for k in keywords] changed to kws = [keywords]

is there any other solution without modifying the plugin?

'sekizai_tags' is not a valid tag library

Hi there. On a clean install in virtualenv this error is thrown in templates. This is my part of reqs.txt. Python 2.7, MacOS X El Capitan.

...
django==1.8.11
django-meta==1.0
...

How can i setup with jinja templates

I'm using jinja2 template in my django project now, But i also want to integrate django-meta in jinja2. as described in docs it is not working with jinja2 templates. But it is working fine with django templates engine

META_SITE_PROTOCOL is not set

I tried implementing the package through a model approach as well as view but in both cases I get this error when I visit the page. According to the documentation, this property is loaded from setting but I have set

SITE_PROTOCOL='https'

I also tried overriding the function in view but that didnt work as well. Any idea how to resolve this?

def get_protocol(self):
        if not settings.SITE_PROTOCOL:
            return 'https'
        else:
            return 'https'
            # raise ImproperlyConfigured('META_SITE_PROTOCOL is not set')
        return settings.SITE_PROTOCOL

og:image and og:image:secure_url

It seems that Facebook does not pick up meta tags with the property og:image and an URL that is secure (https). If I understand correctly, instead the property og:image:secure_url should be used for https. This leads to lost images of any shares of my secure web site on facebook.

Suggestion: Can django-meta check of the URL is secure and add an og:image:secure_url tag in this case?

Similarly og:video and og:audio have secure_url pendants.

Best regards, Fabian

PS: See this Stackoverflow article

Too much blank lines ?

Hi,

using

meta = Meta(
        title="My home",
        url=request.get_full_path(),
        description='My Home page',
        keywords=['wd1', 'wd2', 'wd3', 'wd4'],
        use_og= True,
        use_twitter= True
    )

I get many blank lines between meta tags.

Is there a way to avoid them ?

Thanks

meta tags not showing in head section

Hello, I have installed django-meta 1.6.1 in my project using Django 3.0.5 on localhost (Ubuntu 18.04). I added the following as per the docs:

  1. 'meta' in settings.py
  2. _base.html
{% load sekizai_tags meta %}
<html {% render_block 'html_extra' %}>
<head {% meta_namespaces %}>
  {{ meta.og_description }}
  {% include "meta/meta.html" %}
  {% block css %}
   ....
   ....
  1. Apps View:
from meta.views import Meta
def HomeView(request):
    meta = Meta(
        title="Sam's awesome ponies",
        description='Awesome page about ponies',
        keywords=['pony', 'ponies', 'awesome'],
        extra_props = {
            'viewport': 'width=device-width, initial-scale=1.0, minimum-scale=1.0'
        },
        extra_custom_props=[
            ('http-equiv', 'Content-Type', 'text/html; charset=UTF-8'),
        ]
    )
    .....
    .....

The meta tags are not showing up in head section. Not able to get this working.
Please let me know if there is anything I am missing. Thanks!

how to set use_ variables at model mixin

Hello!

I am using the library to display the meta from a model. The problem is that I do not know how to set the following variables for that case:
use_og
use_twitter
use_facebook
use_googleplus
use_title_tag

I checked the html code and it checks this variables to render the related information; but I can not put them as True from the model.

Thank you!

Default Meta Tags

Hello,

I was wondering/hoping there was a way to set default meta tags, such as for description and title. I see there's a setting for default keywords but not any other type of meta tag. I tried creating a mixin class with various properties that would act as defaults for the meta tags, e.g.:

class DefaultMetaTags:
    title = 'title'
    description = 'meta description'

and

class DefaultMetaTags(MetadataMixin):
    title = 'title'
    description = 'meta description'

but neither seem to do the trick. The goal would be to either set these defaults using a mixin or something in the settings file so I don't have to set these properties on every single view for websites I build. Any help or suggestions would be appreciated, but if it's not possible I can definitely contribute to this project to make it so.

Thanks

Only displayed og:image:secure_url

Hi, after adding secure_url I had a problem. In the specification it is written that from secure_url it is necessary to add also og: image https://ogp.me/. FB debuger say - "The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags."

<meta property="og:image" content="http://example.com/ogp.jpg" />
<meta property="og:image:secure_url" content="https://secure.example.com/ogp.jpg" />

How to use custom function for a meta tag

I want to add something to a meta tag or change it in some way.

I currently do

_metadata = {
        'title' : 'title'
    }
def get_title_meta(self):
    return self.title+ self.topic.title

I'm using title, but I want to use get_title_meta for the title meta tag.

How do I achieve this?

Formatting Tag Output to Include Linebreaks

This may seem like a trivial thing, but is there a way to include a linebreaks after each meta tag generated by the app? I am not sure why this has not been done before, but when one is using Django-Meta, the source-code's meta section of HTML ends up looking like a mess because all the tags are displayed in one line.

Here is a screenshot:

Screenshot from 2020-08-10 12-02-26

Facebook app_id meta formatting

Hello!

I'd like to first say that I've used django-meta on a couple projects now and it's been pretty handy, so thank you for building and sharing it!

Now for the fun stuff—I implemented django-meta on a recent project and I noticed several times that, when plugging pages into the Facebook debug tool:

https://developers.facebook.com/tools/debug/

...it would yell at me about a missing fb:app_id, which I dismissed because I knew it was in there and everything generally looked fine. But yesterday I implemented the Facebook comments plugin:

https://developers.facebook.com/docs/plugins/comments/

...and set up admin/moderators in the Facebook app and it wasn't working—we couldn't moderate any comments. It took me some time, but I noticed a very subtle difference in how django-meta was spitting it out versus how Facebook's documentation was showing it, which was <meta name="fb:app_id" ...> and <meta property="fb:app_id" ...>, respectively. I worked around it by copying meta.html from the source and swapping out the facebook_prop template tag for generic_prop for the app id, but this seems like something that should go in the source.

I believe the proper fix should be to change the facebook_prop template tag to use property instead of name (property seems to be used for all og: tags, not just app_id, which you can see under "Markup Example" here: https://developers.facebook.com/docs/sharing/webmasters ). I'm happy to put up a pull request for this, just say the word.

Thanks!

Add jinja2 support

Django supports Jinja2 natively since 1.8. So it may be nice feature to have.

How to use different data for of OpenGraph and normal tags

I want to display different metadata for facebook and search engines.

Like reddit does.

For example for normal description tag reddit shows "Reddit! The frontpage of the internet".
For OGP it shows "256 points and 56 comments"

ie OGP and normal metadata

How do I do this?

Render Meta attributes with python instead of template

I'm wondering if rendering of Meta objects will be better if they are rendered like widgets Media objects in Django. https://github.com/django/django/blob/master/django/forms/widgets.py#L42

This way there will be no empty new lines for missing properties.
Also I don't think there is something to extend or change in template per project. If something need to be extended probably will be better with Python code. All HTML tags now are not in the template why we need template at all?

What you think about that?

get_meta_image not working?

Hi, all methods like get_meta_description/title/keywords etc. work but get_meta_image does absolutely nothing. Image path is stored in db as a string, and calling self.object.img_url works, too (tested in get_meta_description where self.object.description + self.object.img_url is returned). Any ideas? (Django 1.7, django_meta-0.3.1)

Edit: Just adding some info. I am trying to use og meta tags. <meta property="og:title" ... and <meta property="og:description..." do get displayed in HTML source, og:image does not.

Is META_DEFAULT_IMAGE ignored?

I tried setting META_DEFAULT_IMAGE to something like img/og-image.png which I tested and it's available by /static/img/og-image.png. I also tried setting it to some online available image like http://example.com/image.png — still no luck.

Although, when set the context for meta object like image='img/og-image.png' — it works as expected.

AttributeError _request

For some reason this error happens from time to time. Django 3.x project is running as ASGI

AttributeError: _request
  File "django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "contextlib.py", line 75, in inner
    return func(*args, **kwds)
  File "wagtail/core/views.py", line 24, in serve
    return page.serve(request, *args, **kwargs)
  File "mybaze/core/mixins.py", line 258, in serve
    return view(request, *args, **kwargs)
  File "django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "mybaze/catalog/views.py", line 1062, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "mybaze/catalog/views.py", line 1106, in get
    meta=self.get_meta(),
  File "mybaze/catalog/views.py", line 957, in get_meta
    meta = self.parent_page.as_meta(request=self.request)
  File "meta/models.py", line 102, in as_meta
    for field, data in self._retrieve_data(request, metadata):
  File "meta/models.py", line 72, in _retrieve_data
    yield field, data
  File "contextlib.py", line 120, in __exit__
    next(self.gen)
  File "meta/models.py", line 121, in _set_request
    delattr(self, '_request')

Use of __init__ in MetadataMixin?

edit: see below, this is fixed in the develop branch, but causes problems in the latest stable release, 1.3.1

Removing the __init__ and moving the three variable declarations to class variables fixes a few tricky MRO issues with the view.

It's tricky to create a demonstration, but if it's just a mixin, it may be best to avoid using the constructor.

And second, I'm not sure if there's any point to keeping it, since there's no specialized assignment currently there, and settings is lazily loaded and is ok to put in the class scope.

Error when META_USE_TWITTER_PROPERTIES enable

Description

Error in {% twitter_prop 'domain' meta.get_domain %}. Error message "Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS."

Versions

1.7 in Django 2.0.10

Actual behaviour

Error when META_USE_TWITTER_PROPERTIES enable

MetadataMixin, programmtically generating meta object

Sorry new to django and python, so it's harder for me to debug this.

os: mac osx 10.11.5
django: 1.9
python: 3.4.3

Since your docs say the meta/meta.html partial expects a meta context dict, I'm just trying to programmatically pass that dict into context (preferably without touching each view). I poked through the source and decided to try:

Access get_context_data()

from django.shortcuts import render
from django.views.generic import View
from meta.views import Meta, MetadataMixin

class HomeView(MetadataMixin,View):
    main_template = 'home/main.html'

    def get(self, request):      
        return render(request, self.main_template, context={
            'meta': self.get_context_data(),
        })

error:

'super' object has no attribute 'get_context_data'

context = super(MetadataMixin, self).get_context_data(**kwargs) # this line

Trying to access get_meta():

from django.shortcuts import render
from django.views.generic import View
from meta.views import Meta, MetadataMixin

class HomeView(MetadataMixin,View):
    main_template = 'home/main.html'

    def get(self, request):      
        return render(request, self.main_template, context={
            'meta': self.get_meta(),
        })

error:

Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Perhaps I missed something in the docs, or perhaps I can help improve the docs. Lemme know if you're missing anything!

Support for current domain (from request)

Currently when configuring to use the sites framework it will raise an exception when SITE_ID is not set.

This caused by Site.objects.get_current not being passed the request which is obviously available in both the views and models...

return Site.objects.get_current().domain

Could an optional request be added to the init and passed along?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.