开发者

Passing variables to template based on db

I am trying to add a feature to my app that would allow me to enable/disable the "Call Me" button based on whether or not I am at [home|the office]. I created a model in the database called setting, it looks like this:

class setting(models.Model): 
    key = models.CharField(max_length=200)
    value = models.CharField(max_length=200)

Pretty simple. There is currently one row, available, the value of it is the string True. I want to be able to transparently pass variables to the templates like this:

{% if available %}
   <!-- Display button -->
{% else %}
   <!-- Display grayed out button -->
{% endif %}

Now, I could add logic to every view that would check the database, and pass the variable to the template, but I am trying to stay DRY.

What is the best way to do this?

UPDATE I created a context processor, and added it's path to the TEMPLATE_CONTEXT_PROCESSORS, but it is not being passed to the template

def available(request):
available = Setting.objects.get(key="available")
if open.value == "True":
    return {"available":True}
else:
    return {}

UPDATE TWO If you are using the shortcut render_to_response, you need to pass an instance of RequestContext to the function.

from the django documentation:

If you're using Django's render_to_response() shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not a RequestContext). To use a RequestContext in your开发者_C百科 template rendering, pass an optional third argument to render_to_response(): a RequestContext instance. Your code might look like this:

def some_view(request):
     # ...
     return render_to_response('my_template.html',
                               my_data_dictionary,
                               context_instance=RequestContext(request))

Many thanks for all the help!


Write a custom context processor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜