Getting Site_ID in template Django - python

I have build a web site for a client which has a number of applications. Now he has a new URL registered which he wants to point to the same site, but he wants the look and feel changed. That's basically he wants a new home.html and base.html for the new web site. I can easily add the new site to settings and then change the view for the home page, to display a new home2.html.
However how do I do something like this as expressed in psuedo code in base.html
{% if site_id equals 1 %}
{% include "base1.html" %}
{% endif %}
{% if site_id equals 2 %}
{% include "base2.html" %}
{% endif %}
Any ideas. There are 100s of views on the site and nearly 50 models. I cannot recreate models, and mess around. This needs to be a quick fix.
Thanks in advance

You can create a context processor to automatically add site_id to the context: http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors
But I would opt for a different solution. You can simply add an extra template directory per site so Django will try the templates specifically for that site first and fall back to the normal templates if they're not available.

To extend the idea of WoLph with the context processor, I would maybe even add the switching of the template to the context processor which would clean up your templates, as otherwise you may have to repeat the if clause quite often:
from django.contrib.sites.models import Site
def base_template(request):
site = Site.objects.get_current()
template = "base%s.html" % str(site.pk)
return {'BASE_TEMPLATE': template}
And in your template: {% include BASE_TEMPLATE %}
Looks nicer to me than the switching in the templates!

Another solution would be writing a Middleware to set ´request.site´ the current site id.

Related

Explain the code snippet in Django

I am pretty new to Django. I am fiddling with zinnia to customize it and setting it up with my own theme/template etc. The main content displayed in the default template is following:
{% for object in object_list %}
{% include object.content_template with object_content=object.html_preview continue_reading=1 %}
{% empty %}
I understand that include includes the template inside a page. But what I cannot comprehend is: how do I find the relevant template being rendered? What is content_template? Please help me in understanding this snippet.
The template name (content_template) is being fetched from the database. It is a property of the model ContentTemplateEntry and defaults to zinnia/_entry_detail.html.

Django caching in authenticated sites: best practices

I need to add memcached to my django website.
It's an authenticated website, where different users see different data on the same pages.
Which are the best practices?
I mean, to avoid users to see each other cached pages (information leak)...
I suppose i should use something like:
{% load cache %}
{% cache 500 sidebar request.user.username %}
.. sidebar for logged in user ..
{% endcache %}
or:
#vary_on_cookie
def my_view(request):
# ..
Which is the safest and better way?
It's not the same thing at all, the {% cache %} template tag allows to cache a template fragment and that's used by the server, #vary_on_cookie decorator sets the Vary response header to Cookie, and that's used by the browser.
Also, you could do {% cache 500 sidebar request.user %} instead of specifying the username.

Flask - SubViews

I am looking to use a certain design pattern in my application, but I am not sure if my pattern really even fits with Flask mechanisms. I am just verifying that I have not overlooked existing solutions.
I would like to have a top-level View that renders the response of another proxied request. The thing is, I am not proxying external URLs, but rather views from within my same application (kind of like Blueprints that depend on other Blueprints). Similar to the 'render_template()' function, I am looking for something like render_view, or even better, *request_view_as_string*. I then need to process the response and re-render.
I am using template inheritance to the best of my abilities (jinja2), but much of my difficulty is coming from lots of non-template processing in between the template blocks. I am still getting a feel for jinja, and my templates are starting to feel polluted with hacks.
Edit
Basically, I misunderstood the role of jinja. My application needs to build heavier on jinja. I kept trying to get in and out of jinja as quickly as possible, and that is where my nested dependencies were starting to cause problems. Ultimately, most of the features I needed for my "subviews" was built right into Jinja, I just wasn't sure how to properly integrate them with FLask.
First off, Jinja2 supports macros, which let you share functionality between templates:
{# helpers.jinja #}
{% macro generate_select(itrbl) %}
<select{{kwargs|xmlattrs}}>
{% for item in itrbl %}
<option value="{{item.value}}">{{item.text}}</option>
{% endfor %}
</select>
{% endmacro %}
{# page1.jinja #}
{% import "helpers.jinja" as helpers %}
{{ helpers.generate_select(data, name="my_data_field") }}
For more complicated bits of functionality (A / B testing, loading different features depending on what the user's account has enabled, etc.) extends, include, and import can take variable values:
{# A custom template with a *lot* of hooks #}
{% extends base_template %}
{% import custom_functionality_provider as provider %}
{% block common_name %}
{% if features.feature_x %}
{% include feature_x_include %}
{% endif %}
{{ provider.operation() }}
{% endblock common_name %}
#app.route("/some-route")
def some_route():
# Of course, in real life you would determine these values
# on the basis of user / condition lookups, rather than
# hardcoding values in your render_template call
render_template("custom.jinja", base_template="AB/A/base.jinja",
custom_functionality_provider="macros/lowcostplan.jinja",
feature_x_include="AB/A/features/feature_x.jinja",
features=some_features_object)
Finally, you can pass callables that return strings to any Jinja template, giving you access to the full power of Python:
def custom_implimentation_a(**context_args):
return render_template("template_a.jinja", **context_args)
def custom_implimentation_b(**context_args):
return render_template("template_b.jinja", **context_args)
#app.route("/some-route")
def some_route():
if condition:
provider = custom_implimentation_a # Note, no parenthesis
else:
provider = custom_implimentation_b
return render_template("some_page.jinja", provider=provider)
I do consider Sean's first answer as the most appropriate, but I did run across this little mechanism for those times when Jinja is making Python tasks a bit difficult.
http://werkzeug.pocoo.org/docs/local/
This should be a little more productive than Flask's g variable. See also a slightly different usage (when one global 'namespace' is no longer manageable)
http://flask.pocoo.org/snippets/13/
I very often forget that Flask and Werkzeug are related projects. The huge benefit of this is that much of their functionality does not overlap with the other project.
When you are newbie approaching from the Flask side, if you feel like Flask is missing a few gears, there is a good chance its because they already included them in Werkzeug.

Django template check for empty when I have an if inside a for

I have the following code in my template:
{% for req in user.requests_made_set.all %}
{% if not req.is_published %}
{{ req }}
{% endif %}
{% empty %}
No requests
{% endfor %}
If there are some requests but none has the is_published = True then how could I output a message (like "No requests") ?? I'd only like to use Django templates and not do it in my view!
Thanks
Even if this might be possible to achieve in the template, I (and probably many other people) would advise against it. To achieve this, you basically need to find out whether there are any objects in the database matching some criteria. That is certainly not something that belongs into a template.
Templates are intended to be used to define how stuff is displayed. The task you're solving is determining what stuff to display. This definitely belongs in a view and not a template.
If you want to avoid placing it in a view just because you want the information to appear on each page, regardless of the view, consider using a context processor which would add the required information to your template context automatically, or writing a template tag that would solve this for you.

Overriding Django Admin's main page? - Django

I'm trying to add features to Django 1.2 admin's main page.
I've been playing with index.html, but features added to this page affect all app pages.
Any ideas on what template I'm supposed to use?
Thanks loads!!
You can use template hierarchy like:
index.html
...
{% block content %}
...
{% block mycontent %}My custom text{% endblock %}
...
{% endblock %}
app_index.html
...
{% block mycontent %}{% endblock %}
..
According to http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template you will want to override admin/app_index.html
I have done this by modifying the admin/index.html template. You may also need to modify admin/base_site.html (depending on what you want to do, exactly).
These templates are found in the django/contrib/admin/templates/admin folder in a Django installation.
Update: That's exactly what I've done, see the screenshot fragment below. The section marked in red is the section I added, via HTML in admin/index.html. However, you don't say which version of Django you're using - my example is from a 1.0 installation.

Categories

Resources