Skip to content

Commit c33250e

Browse files
author
Ivan Gromov
committed
Changed URL-fallback behavior.
2 parents 2e98631 + bf06779 commit c33250e

File tree

1 file changed

+30
-21
lines changed

1 file changed

+30
-21
lines changed

seo/templatetags/seo_tags.py

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# -*- coding: utf-8 -*-
2-
import warnings
32
from django import template
43
from django.contrib.contenttypes.models import ContentType
54
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
65
from django.http import HttpRequest
76
from django.template.loader import render_to_string
87
from django.utils.html import escape
98
from seo.models import Seo, Url
9+
import warnings
1010

1111
INTENTS = ['title', 'keywords', 'description', ]
1212

@@ -18,35 +18,44 @@ def __init__(self, intent, object, variable):
1818
self.object = object
1919
self.variable = variable
2020

21+
def _process_var_argument(self, context):
22+
if self.variable is None:
23+
return escape(getattr(seo, self.intent))
24+
else:
25+
context[self.variable] = getattr(seo, self.intent)
26+
return u''
27+
2128
def render(self, context):
2229
if self.object is None:
23-
object = None
30+
# search by URL
31+
try:
32+
request = context['request']
33+
except KeyError:
34+
warnings.warn('`request` was not found in context. Add "django.core.context_processors.request" to `TEMPLATE_CONTEXT_PROCESSORS` in your settings.py.')
35+
else:
36+
object = Url.objects.get(url=request.path_info)
37+
seo = Seo.objects.get(
38+
content_type=ContentType.objects.get_for_model(
39+
object.__class__),
40+
object_id=object.id)
41+
return self._process_var_argument(context)
42+
2443
else:
44+
# Tyr to retrieve object from context
2545
object = template.Variable(self.object).resolve(context)
26-
try:
27-
if object is None:
28-
raise ObjectDoesNotExist
29-
seo = Seo.objects.get(
30-
content_type=ContentType.objects.get_for_model(
31-
object.__class__),
32-
object_id=object.id)
33-
except ObjectDoesNotExist:
34-
if 'request' not in context:
35-
warnings.warn('`request` was not found in context. Is "django.core.context_processors.request" enabled in `TEMPLATE_CONTEXT_PROCESSORS`?')
36-
path_info = context['request'].path_info
3746
try:
38-
object = Url.objects.get(url=path_info)
3947
seo = Seo.objects.get(
4048
content_type=ContentType.objects.get_for_model(
4149
object.__class__),
4250
object_id=object.id)
43-
except ObjectDoesNotExist:
44-
seo = Seo()
45-
if self.variable is None:
46-
return escape(getattr(seo, self.intent))
47-
else:
48-
context[self.variable] = getattr(seo, self.intent)
49-
return u''
51+
except Seo.DoesNotExist:
52+
raise
53+
else:
54+
return self._process_var_argument(context)
55+
56+
# silent fallback
57+
return u''
58+
5059

5160
def seo_tag(parser, token):
5261
"""Get seo data for object"""

0 commit comments

Comments
 (0)