EzDevInfo.com

django-templates interview questions

Top django-templates frequently asked interview questions

How do I use Django templates without the rest of Django?

I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

If I run the following code:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

I get:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Source: (StackOverflow)

How to access outermost forloop.counter with nested for loops in Django templates?

Is it possible to access the forloop.counter for the outermost for loop in the following template in Django:

{% for outerItem in outerItems %}
    {% for item in items%}
        <div>{{ forloop.counter }}.&nbsp;{{ item }}</div>
    {% endfor %}
{% endfor %}

forloop.counter returns the innermost for loop's counter in the above example


Source: (StackOverflow)

Advertisements

How to access the user profile in a Django template?

I'm storing some additional per-user information using the AUTH_PROFILE_MODULE.

We can access the user in a Django template using {{ request.user }} but how do we access fields in the profile since the profile is only accessible via a function user.get_profile() ?

Is it really required to explicitly pass the profile into the template every time?


Source: (StackOverflow)

AngularJS with Django - Conflicting template tags

I want to use AngularJS with Django however they both use {{ }} as their template tags. Is there an easy way to change one of the two to use some other custom templating tag?


Source: (StackOverflow)

Can I access constants in settings.py from templates in Django?

I have some stuff in settings.py that I'd like to be able to access from a template, but I can't figure out how to do it. I already tried

{{CONSTANT_NAME}}

but that doesn't seem to work. Is this possible?


Source: (StackOverflow)

Numeric for loop in Django templates

How do I write a numeric for loop in a Django template? I mean something like

for i = 1 to n

Source: (StackOverflow)

How to set a value of a variable inside a template code?

Say I have a template

<html>
<div>Hello {{name}}!</div>
</html>

While testing it, it would be useful to define the value of the variable without touching the python code that invokes this template. So I'm looking for something like this

{% set name="World" %}     
<html>
<div>Hello {{name}}!</div>
</html>

Does something like this exists in Django?

Thanks


Source: (StackOverflow)

Can we append to a {% block %} rather than overwrite?

In my core.html I have a block labeled javascript. It would be great if I can append more lines to this block without overwriting everything in it.


Source: (StackOverflow)

Is there a HAML implementation for use with Python and Django

I happened to stumble across HAML, an interesting and beautiful way to mark up contents and write templates for HTML.

Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.


Source: (StackOverflow)

How to get form field's id in Django?

Is there any way to get the id of a field in a template?

In the HTML i get: <input name="field_name" id="id_field_name"...

I know I can get the name with {{ field.html_name }}, but is there anything similar for getting the id?
Or can I only get it like this: id_{{ field.html_name }}?


Source: (StackOverflow)

How do I perform query filtering in django templates

I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:

queryset = Modelclass.objects.filter(somekey=foo)

In my template I would like to do

{% for object in data.somekey_set.FILTER %}

but I just can't seem to find out how to write FILTER.


Source: (StackOverflow)

Django Template Variables and Javascript

When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.

Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.

Many thanks,

Alistair.


Source: (StackOverflow)

Iterate over model instance field names and values in template

I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.

For example, let's say we have the following model definition:

class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")

I would want it to be output in the template like so (assume an instance with the given values):

Field Name      Field Value
----------      -----------
Name            Wayne Koorts
E-mail          waynes@email.com

What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:

<table>
    {% for field in fields %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>

Is there a neat, "Django-approved" way to do this? It seems like a very common task, and I will need to do it often for this particular project.


Source: (StackOverflow)

How to repeat a "block" in a django template

I want to use the same {% block %} twice in the same django template. I want this block to appear more than once in my base template:

# base.html
<html>
    <head>
        <title>{% block title %}My Cool Website{% endblock %}</title>
    </head>
    <body>
        <h1>{% block title %}My Cool Website{% endblock %}</h1>
    </body>
</html>

And then extend it:

# blog.html
{% extends 'base.html' %}
{% block title %}My Blog{% endblock %}

# pictures.html
{% extends 'base.html' %}
{% block title %}My Pictures{% endblock %}

# cats.html
{% extends 'base.html' %}
{% block title %}My Cats{% endblock %}

I will get an exception, as Django wants the block to appear only once:

TemplateSyntaxError at /

'block' tag with name 'title' appears more than once

A quick and dirty solution would be duplicating the block title into title1 and title2:

# blog.html
{% extends 'base.html' %}
{% block title1 %}My Blog{% endblock %}
{% block title2 %}My Blog{% endblock %}

But this is a violation of the DRY principle. It would be very difficult as I have a lot of inheriting templates, and also because I don't wanna go to hell ;-)

Is there any trick or work-around to this problem? How can I repeat the same block in my template, without duplicating all the code?


Source: (StackOverflow)

Django templates: verbose version of a choice

I have a model:

from django.db import models

CHOICES = (
    ('s', 'Glorious spam'),
    ('e', 'Fabulous eggs'),
)

class MealOrder(models.Model):
    meal = models.CharField(max_length=8, choices=CHOICES)

I have a form:

from django.forms import ModelForm

class MealOrderForm(ModelForm):
    class Meta:
        model = MealOrder

And I want to use formtools.preview. The default template prints the short version of the choice ('e' instead of 'Fabulous eggs'), becuase it uses

{% for field in form %}
<tr>
<th>{{ field.label }}:</th>
<td>{{ field.data }}</td>
</tr>
{% endfor %}.

I'd like a template as general as the mentioned, but printing 'Fabulous eggs' instead.

[as I had doubts where's the real question, I bolded it for all of us :)]

I know how to get the verbose version of a choice in a way that is itself ugly:

{{ form.meal.field.choices.1.1 }}

The real pain is I need to get the selected choice, and the only way coming to my mind is iterating through choices and checking {% ifequals currentChoice.0 choiceField.data %}, which is even uglier.

Can it be done easily? Or it needs some template-tag programming? Shouldn't that be available in django already?


Source: (StackOverflow)