Django: How to import variables in html templates - python

I have a django application and what I want to do is change wherever it says "Company id" in my templates. The thing it can be very tedious because I have to make this change in every template which says "Company id". So then I thought I might create another file that can store this entry, which the I can easy custom the company id.
config.py
company_no = "Company id"
This can work in my forms.py file. I can import company_no by saying
forms.py
from mmc.config import company_no
But then how can I do the same thing for templates? Importing company_no in a template - is there a way round?

This is what context processors are for. Define your company name in settings.py, then write a context processor that imports it from there and returns it in a dictionary - it will then be available in every template (as long as you use RequestContext to render the template).

As Blender stated, you need to pass variables like this in as part of the context when you render the template. You might make a dictionary or a namedtuple that has common items stored in configuration loaded in a function.
You should also consider using template inheritance if many templates will be display the same data, then you can have methods that load the pieces of context that go with certain base templates.

You could create a shared template and use include to load it in to the main template. Then in the shared template you could load and call a custom template tag that produces a context variable and render it as usual.
Alternatively, you could create a custom context processor that loads the data automatically in to the context instance and then render it as usual in the shared template.

Related

Make an object exists in all templates

I have a django and I wrote some views. I know how to pass my variables to template, but I also has some external modules with their own views, which I wont modify. Please help me understand how can I get one of my object "Menu.objects.all()" exist in all templates? So for example a I have django-registration and i want to have all my menu items appear at top when someone visits not my app url. I mean it will be registration app url, which returns templateresponse (and here I dont have my variable).
You can add variables to context
The cleanest way to do it, is to use a Template Context Processor, which is a hook that will allow you to add things to your context before the template is rendered.
http://www.djangobook.com/en/2.0/chapter09.html
https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors
Here's an example of Template Context Processors used in the django core:
https://github.com/django/django/blob/master/django/template/context_processors.py

Access Model.objects methods from Django templates

Let's say I have a "Person" model.
How can I display the number of persons in my system in a template?
In standard code, I would do: Person.objects.count().
But how to do this in a template?
You save the output of Person.objects.count() in a variable and pass it on to your template from the corresponding view.

Django Rendering Template Included in a Template

Basically I have a base template, and the base template is including another template, let's say, latest update. So the structure is like this:
-base.html
|---------latest_update.html
So, I know how to include a simple template, like the template without any data processing (doesn't require interaction with any application view.py). However, how could I attach the included template into a django application view.py so that I could at least show updated data periodically?
I am not exactly sure terms for this, feel free to change the title.
Edit: This question is a bit cloudy, as I don't know how to put the terminology correctly. So, I have this included template. Every page will have it. So, from my limited knowledge, that means I have to render it manually for every page that hits view.py. Is there any easier way of doing this?
You can use Django templatetags. Define a file named latest_update_tags under your Django app templatetags directory and write code like this to define a latest_update templatetags:
from django import template
from app.models import UpdateObject
register = template.Library()
#register.inclusion_tag("latest_update.html")
def latest_update():
update_objects = UpdateObject.all().[:10]
return {"update_objects": update_objects}
And then in your base.html use it like this:
{% load latest_update_tags %}
......
{% latest_update %}

how do you style a form already inside django

I'm using django-registration. I'd like to update the AuthenticationForm in 'django.contrib.auth.forms'. Specifically, I would like to pass the 'attrs' dict to add a few attributes. How do I update a form that comes with django?
You can use the views that come with auth and override the form parameter with your own form:
django.contrib.auth.views.login(request[, template_name, redirect_field_name, authentication_form])
More info here.
The standard way is to subclass AuthenticationForm, change the attrs in constructor, pass the form to login view and write a new entry in urls.py.
This is a nightmare: in order to add html attribute to a field it is necessary to use python subclassing, to know how exactly django's form metaclass work (self.fields['field'].widget.attrs, not just self.field.widget.attrs), to know regexes (for urls.py), to know how django's urls.py work (should you put the overriding line before of after include('django.contrib.auth.urls')?) and to know where is the auth form and auth view imported from.
And now the "commercial break": just use http://pypi.python.org/pypi/django-widget-tweaks for your task ;)

Django.contrib.flatpages without models

I have some flatpages with empty content field and their content inside the template (given with template_name field).
Why I am using django.contrib.flatpages
It allows me to serve (mostly) static pages with minimal URL configuration.
I don't have to write views for each of them.
Why I don't need the model FlatPage
I leave the content empty and just supply a template path. Therefore I can take advantage of having the source in a file;
I can edit the source directly from the file system, without the help of a server (such as admin).
I can take advantage of syntax highlightning and other editor features.
With the model I have to maintain fixtures for flatpages.
So the data for the same entity is in two seperate places.
If I move the content inside the fixture it'll be more difficult to edit.
Even if fixture maintenance was a non-issue I'd still need to dump and load these fixtures again and again during development.
What I am looking for
Basically; getting rid of FlatPage model while maintaining contrib.flatpages functionality. I don't have a clear idea how this should be solved. If there's a clean way of modifying (like add_to_class) FlatPages to get the information somewhere other than the database I'd prefer that. Maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of FlatPages.
If I don't prefer manual editing over admin functionality for flatpages, how can take the database out of the equation?
Using the direct_to_template generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:
r'^foo/(?P<template_name>.+)/$','direct_to_template', {'template': 'foo_index.html'}),
Then import the template in your foo_index.html:
{% include template_name %}

Categories