Django + decorators: Adding context to the template based on a criteria
I'm not开发者_C百科 sure if decorators are the best way to do this, but I've removed the idea of using context processors and I'm not sure if a middleware is what I'd like.
My situation is as follows: We process sales and other data daily. Every month, we close the month off just like any other business. We do this on paper, but I would like to apply the same thing to our system. So basically, make data read-only if it falls within the closed off date.
I've easily figured out how to do this on the processing/backend side, but how would I pass such a context to a template without editing a ton of my view functions? I simply want to pass a decorator to my functions that will test the date of the instance that's being passed and add some context to the template so I can display a little message, letting the user know why the "Save" button is blanked out.
I hope my question makes sense. Thanks in advance.
I would use a custom template tag. It makes it very easy to set context variables
#yourapp/templatetags/business_tags.py
from django import template
register = template.Library()
class BusinessNode(template.Node):
def __init__(self, instance, varName):
self.instance, self.varName=instance, varName
def render(self, context):
instance=template.Variable(self.instance).render(context)
if instance.passes_some_test():
context[self.varName]='Some message'
else:
context[self.varName]="Some other message"
return ''
@register.tag
def business_check(parser, token):
bits=token.split_contents()
if len(bits)==5:
return BusinessNode(bits[2],bits[4])
return ''
Then in your template
{% load business_tags %}
{% business_check for someVar as myMessage %}
{{myMessage}}
This works equally well for inserting other types of data into the context.
精彩评论