Re: templatetags and refresh
On Jun 24, 4:02 pm, Wim Feijenwrote: > Thanks Bruno for your detailed advice and attention! > Sorry I didn't have time to provide relevant pointers (which I usually do) :-/ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: templatetags and refresh
Thanks Bruno for your detailed advice and attention! I agree wholeheartedly. Wim On Jun 24, 12:53 pm, bruno desthuillierswrote: > On Jun 24, 11:57 am,WimFeijen wrote: > > > > > Looking at it again, I saw what was wrong and fixed it! For > > completeness, I moved the NewsItem query within the NewsItemBlockNode > > FWIW, code at the module top-level is only executed when the module is > first imported. Now you'll know ;) > > > > > > > > > > > and everything works fine! The current code is: > > > import re > > > from django.template import Variable, VariableDoesNotExist, Node, > > Library, Template, TemplateSynta > > from django.conf import settings > > from django.utils.safestring import mark_safe > > from django.utils.html import escape > > from django.utils.translation import ugettext as _ > > > register = Library() > > > from cms.news.models import NewsItem > > from django.db.models import Q > > from datetime import datetime > > > class NewsItemBlockNode(Node): > > def __init__(self, identifier, field): > > self.identifier = str(identifier) > > self.field = str(field) > > self.image = False > > > def render(self, context): > > try: > > newsitems = NewsItem.objects.filter(Q(expires_at__gt = > > datetime.now()) | Q(expires_at_ > > except: > > Never use a bare except clause, unless you reraise the exception. > > > > > > > > > > > newsitems = None > > > number = -1 > > numbers = { > > 'large': 0, > > 'large-small': 0, > > 'small1': 1, > > 'small2': 2, > > 'small3': 3, > > 'small4': 4, > > 'medium': 5, > > } > > > # Only image > > if self.field == 'teaser-image': > > self.field = 'teaser' > > self.image = True > > Never change a Node's attributes from within the render method - this > will screw you sooner or later. Use local variables instead (with the > added bonus of improved performances - local variables are way faster > than attribute lookups). > > > if self.identifier in numbers: > > number = numbers[self.identifier] > > > try: > > newsitem = getattr(newsitems[number], self.field) > > > if type(newsitem).__name__ == 'datetime': > > you may want to read about "isintance" > > > if self.identifier in ['medium', 'large']: > > use a tuple instead of a list - it's cheaper. > > > newsitem = newsitem.strftime('%d [%m] %Y') > > > newsitem = newsitem.replace('[01]', 'januari') > > newsitem = newsitem.replace('[02]', 'februari') > > newsitem = newsitem.replace('[03]', 'maart') > > newsitem = newsitem.replace('[04]', 'april') > > newsitem = newsitem.replace('[05]', 'mei') > > newsitem = newsitem.replace('[06]', 'juni') > > newsitem = newsitem.replace('[07]', 'juli') > > newsitem = newsitem.replace('[08]', 'augustus') > > newsitem = newsitem.replace('[09]', 'september') > > newsitem = newsitem.replace('[10]', 'oktober') > > newsitem = newsitem.replace('[11]', 'november') > > newsitem = newsitem.replace('[12]', 'december') > > You may want to have a read at Django's and Python's localisation > features... > > > newsitem = newsitem.upper() > > else: > > newsitem = newsitem.strftime('%d-%m-%Y') > > > if self.image: > > # Filter only image > > src = re.search('', newsitem) > > regexps are not the safest way to parse html. > > > if src and src.group(2): > > newsitem = src.group(2) > > else: > > newsitem = '/media/site/img/blank.gif' > > Use named urls and reverse() instead - unless you are happy with > maintenance headache, of course ;) > > > elif self.field == 'teaser': > > # Filter image > > newsitem = re.sub('', '', newsitem) > > newsitem = re.sub(' ', '', newsitem) > > newsitem = re.sub('', '', newsitem) > > newsitem = re.sub('', '', newsitem) > > Proverbial SquaredWheel alert. Django (and Python) have safer ways to > strip a text from HTML tags and entities. > > > except: > > Same as above. Exceptions and traceback are here to HELP you fixing > your code, so don't shoot yourself in the foot by silently passing > them. > > HTH -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to
Re: templatetags and refresh
On Jun 24, 11:57 am, Wim Feijenwrote: > > Looking at it again, I saw what was wrong and fixed it! For > completeness, I moved the NewsItem query within the NewsItemBlockNode FWIW, code at the module top-level is only executed when the module is first imported. Now you'll know ;) > and everything works fine! The current code is: > > import re > > from django.template import Variable, VariableDoesNotExist, Node, > Library, Template, TemplateSynta > from django.conf import settings > from django.utils.safestring import mark_safe > from django.utils.html import escape > from django.utils.translation import ugettext as _ > > register = Library() > > from cms.news.models import NewsItem > from django.db.models import Q > from datetime import datetime > > class NewsItemBlockNode(Node): > def __init__(self, identifier, field): > self.identifier = str(identifier) > self.field = str(field) > self.image = False > > def render(self, context): > try: > newsitems = NewsItem.objects.filter(Q(expires_at__gt = > datetime.now()) | Q(expires_at_ > except: Never use a bare except clause, unless you reraise the exception. > newsitems = None > > number = -1 > numbers = { > 'large': 0, > 'large-small': 0, > 'small1': 1, > 'small2': 2, > 'small3': 3, > 'small4': 4, > 'medium': 5, > } > > # Only image > if self.field == 'teaser-image': > self.field = 'teaser' > self.image = True Never change a Node's attributes from within the render method - this will screw you sooner or later. Use local variables instead (with the added bonus of improved performances - local variables are way faster than attribute lookups). > if self.identifier in numbers: > number = numbers[self.identifier] > > try: > newsitem = getattr(newsitems[number], self.field) > > if type(newsitem).__name__ == 'datetime': you may want to read about "isintance" > if self.identifier in ['medium', 'large']: use a tuple instead of a list - it's cheaper. > newsitem = newsitem.strftime('%d [%m] %Y') > > newsitem = newsitem.replace('[01]', 'januari') > newsitem = newsitem.replace('[02]', 'februari') > newsitem = newsitem.replace('[03]', 'maart') > newsitem = newsitem.replace('[04]', 'april') > newsitem = newsitem.replace('[05]', 'mei') > newsitem = newsitem.replace('[06]', 'juni') > newsitem = newsitem.replace('[07]', 'juli') > newsitem = newsitem.replace('[08]', 'augustus') > newsitem = newsitem.replace('[09]', 'september') > newsitem = newsitem.replace('[10]', 'oktober') > newsitem = newsitem.replace('[11]', 'november') > newsitem = newsitem.replace('[12]', 'december') You may want to have a read at Django's and Python's localisation features... > newsitem = newsitem.upper() > else: > newsitem = newsitem.strftime('%d-%m-%Y') > > if self.image: > # Filter only image > src = re.search('', newsitem) regexps are not the safest way to parse html. > if src and src.group(2): > newsitem = src.group(2) > else: > newsitem = '/media/site/img/blank.gif' Use named urls and reverse() instead - unless you are happy with maintenance headache, of course ;) > elif self.field == 'teaser': > # Filter image > newsitem = re.sub('', '', newsitem) > newsitem = re.sub(' ', '', newsitem) > newsitem = re.sub('', '', newsitem) > newsitem = re.sub('', '', newsitem) Proverbial SquaredWheel alert. Django (and Python) have safer ways to strip a text from HTML tags and entities. > except: Same as above. Exceptions and traceback are here to HELP you fixing your code, so don't shoot yourself in the foot by silently passing them. HTH -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: templatetags and refresh
Thanks! That helped. :) The code for the tag was as follows: import re from django.template import Variable, VariableDoesNotExist, Node, Library, Template, TemplateSyntaxError, Context, loader from django.conf import settings from django.utils.safestring import mark_safe from django.utils.html import escape from django.utils.translation import ugettext as _ register = Library() from cms.news.models import NewsItem from django.db.models import Q from datetime import datetime try: # newsitems = NewsItem.objects.all().order_by('-created_at') # newsitems = NewsItem.objects.visible().order_by('- news_timestamp') newsitems = NewsItem.objects.filter(Q(expires_at__gt = datetime.now()) | Q(expires_at__isnull = True), effective_at__lte = datetime.now(), is_active=True).order_by('-news_timestamp') except: newsitems = None class NewsItemBlockNode(Node): def __init__(self, identifier, field): self.identifier = str(identifier) self.field = str(field) self.image = False def render(self, context): global newsitems number = -1 numbers = { 'large': 0, 'large-small': 0, 'small1': 1, 'small2': 2, 'small3': 3, 'small4': 4, 'medium': 5, } # Only image if self.field == 'teaser-image': self.field = 'teaser' self.image = True if self.identifier in numbers: number = numbers[self.identifier] try: newsitem = getattr(newsitems[number], self.field) if type(newsitem).__name__ == 'datetime': if self.identifier in ['medium', 'large']: newsitem = newsitem.strftime('%d [%m] %Y') newsitem = newsitem.replace('[01]', 'januari') newsitem = newsitem.replace('[02]', 'februari') newsitem = newsitem.replace('[03]', 'maart') newsitem = newsitem.replace('[04]', 'april') newsitem = newsitem.replace('[05]', 'mei') newsitem = newsitem.replace('[06]', 'juni') newsitem = newsitem.replace('[07]', 'juli') newsitem = newsitem.replace('[08]', 'augustus') newsitem = newsitem.replace('[09]', 'september') newsitem = newsitem.replace('[10]', 'oktober') newsitem = newsitem.replace('[11]', 'november') newsitem = newsitem.replace('[12]', 'december') newsitem = newsitem.upper() else: newsitem = newsitem.strftime('%d-%m-%Y') if self.image: # Filter only image src = re.search('', newsitem) if src and src.group(2): newsitem = src.group(2) else: newsitem = '/media/site/img/blank.gif' elif self.field == 'teaser': # Filter image newsitem = re.sub('', '', newsitem) newsitem = re.sub('', '', newsitem) newsitem = re.sub('', '', newsitem) newsitem = re.sub('', '', newsitem) except: newsitem = '' return mark_safe(newsitem) @register.tag() def show_newsitem(parser, token): try: tag, identifier, field = token.split_contents() except ValueError: raise TemplateSyntaxError('%s needs newsitem number (x latest newsitem) as an argument.' % tag) return NewsItemBlockNode(identifier, field) -- Looking at it again, I saw what was wrong and fixed it! For completeness, I moved the NewsItem query within the NewsItemBlockNode and everything works fine! The current code is: import re from django.template import Variable, VariableDoesNotExist, Node, Library, Template, TemplateSynta from django.conf import settings from django.utils.safestring import mark_safe from django.utils.html import escape from django.utils.translation import ugettext as _ register = Library() from cms.news.models import NewsItem from django.db.models import Q from datetime import datetime class NewsItemBlockNode(Node): def __init__(self, identifier, field): self.identifier = str(identifier) self.field = str(field) self.image = False def render(self, context): try: # newsitems = NewsItem.objects.all().order_by('- created_at') # newsitems = NewsItem.objects.visible().order_by('- news_timestamp') newsitems = NewsItem.objects.filter(Q(expires_at__gt = datetime.now()) | Q(expires_at_ except: newsitems = None number = -1 numbers = { 'large': 0, 'large-small': 0, 'small1': 1, 'small2': 2,
Re: templatetags and refresh
On Wednesday, 22 June 2011 14:32:10 UTC+1, Wim Feijen wrote: > > Hello, > > At www.mkb-rotterdam.nl we use a template tag to display NewsItems in > different formats on the homepage. > > However, when a new NewsItem is added, it does not appear at once. > > Might this have to do with the fact that we use a template tag to get > the NewsItems out of the db? > > Our query is: > > newsitems = NewsItem.objects.filter(Q(expires_at__gt = datetime.now()) > | Q(expires_at__isnull = True), effective_at__lte = datetime.now(), > is_active=True).order_by('-news_timestamp') > > Or is datetime.now() fixed to the past? > > What would be a proper way to solve this then? Maybe add a post-save > signal but how could we use this then to refresh the tag? > > If something else is the matter, or just if you're interested: we host > our site using a virtual apache + mod_wsgi + nginx. > > Thanks for your help! > > Wim > > > Please show the full code for the templatetag. -- DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/-9ELyqjEGxwJ. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: templatetags and refresh
Dnia 2011-06-22, śro o godzinie 06:32 -0700, Wim Feijen pisze: > Our query is: > > newsitems = NewsItem.objects.filter(Q(expires_at__gt = datetime.now()) > | Q(expires_at__isnull = True), effective_at__lte = datetime.now(), > is_active=True).order_by('-news_timestamp') > > Or is datetime.now() fixed to the past? You're probably gonna have to elaborate on your code, but did you try datetime.now without calling it? IIUC that helps here and there, not sure it will in your particular case. -- Michał (Saviq) Sawiczsignature.asc Description: This is a digitally signed message part
templatetags and refresh
Hello, At www.mkb-rotterdam.nl we use a template tag to display NewsItems in different formats on the homepage. However, when a new NewsItem is added, it does not appear at once. Might this have to do with the fact that we use a template tag to get the NewsItems out of the db? Our query is: newsitems = NewsItem.objects.filter(Q(expires_at__gt = datetime.now()) | Q(expires_at__isnull = True), effective_at__lte = datetime.now(), is_active=True).order_by('-news_timestamp') Or is datetime.now() fixed to the past? What would be a proper way to solve this then? Maybe add a post-save signal but how could we use this then to refresh the tag? If something else is the matter, or just if you're interested: we host our site using a virtual apache + mod_wsgi + nginx. Thanks for your help! Wim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.