What is the equivalent of "none" in django templates? - python

I want to see if a field/variable is none within a Django template. What is the correct syntax for that?
This is what I currently have:
{% if profile.user.first_name is null %}
<p> -- </p>
{% elif %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}
In the example above, what would I use to replace "null"?

None, False and True all are available within template tags and filters. None, False, the empty string ('', "", """""") and empty lists/tuples all evaluate to False when evaluated by if, so you can easily do
{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}
A hint: #fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:
# someapp/models.py
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
# other fields
def get_full_name(self):
if not self.user.first_name:
return
return ' '.join([self.user.first_name, self.user.last_name])
# template
{{ user.get_profile.get_full_name }}

You can also use another built-in template default_if_none
{{ profile.user.first_name|default_if_none:"--" }}

You can also use the built-in template filter default:
If value evaluates to False (e.g. None, an empty string, 0, False); the default "--" is displayed.
{{ profile.user.first_name|default:"--" }}
Documentation:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default

isoperator : New in Django 1.10
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}

Look at the yesno helper
Eg:
{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

{% if profile.user.first_name %} works (assuming you also don't want to accept '').
if in Python in general treats None, False, '', [], {}, ... all as false.

In cases where we need to validate for a field with null value, we may check so and process as under:
{% for field in form.visible_fields %}
{% if field.name == 'some_field' %}
{% if field.value is Null %}
{{ 'No data found' }}
{% else %}
{{ field }}
{% endif %}
{% endif %}
{% endfor %}

You could try this:
{% if not profile.user.first_name.value %}
<p> -- </p>
{% else %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}
This way, you're essentially checking to see if the form field first_name has any value associated with it. See {{ field.value }} in Looping over the form's fields in Django Documentation.
I'm using Django 3.0.

Just a note about previous answers: Everything is correct if we want to display a
string, but pay attention if you want to display numbers.
In particular when you have a 0 value bool(0) evaluates to False and so it will not display and probably is not what you want.
In this case better use
{% if profile.user.credit != None %}

Related

django janja compare database value

I have some data store in the database In boolean. I want to check if the value is True pick the value and perform some action on it.
product: "{{DB_report_query.product.name}}"
{% if DB_report_query.product.summary == True %}
{{DB_report_query.summary}}
{% endif %}
But this does not work.
If it is a BooleanField then simply use the following:
{% if DB_report_query.product.summary %}
{{DB_report_query.summary}}
{% endif %}

Tag inside tag Django template

First of all, let me show our views.py file.
context = {
'id' : id,
'durum' : durum,
'range': range(len(id)),
}
I have such data in template;
context.id = [12, 10, 10]
context.durum = ['UPL','PPL','FIUPL']
I want to match this data like this;
12 UPL
10 PPL
10 FIUPL
I created a for loop for this, but need to edit
{% for i in context.range %}
{{ context.id }}
{{ context.durum }}
{% endfor %}
Like this;
{% for i in context.range %}
{{ context.id.i }}
{{ context.durum.i }}
{% endfor %}
But I can't use the variable i in the loop.
Use zip in view
Ex:
context = {
'data' : zip(id, durum)
}
And then in template
Use:
{% for id, durum in data %}
{{ id }}
{{ durum }}
{% endfor %}
You can use list comprehension.
So, for example:
my_list = list(zip(context['id'], context['durum'], context['range']))
And then in the template, you can use:
{% for item in my_list %}
{{ item.0 }} -- { item.1 }}
{% endfor %}
Well, it seems like you moved to python from some other language. You don't usually use indexing in python for loops (they are much easier and more intuitive) that's why it was hard for you to 'pair' those values. If you still can refactor your code, instead of making to list with attributes on matching indexes use a dict. One - it will let you unpack really easily in django template
{% for id, durum in my_dict %}
{{ id }} {{ durum }}
{% endfor %}
Two - it will prevent any errors connected with wrong index because you just call id and it will get the right durum. Three - it will be very easy to update such data set.
my_dict.update({new_id: new_durum})
Please consider spending a little bit of time learning new stuff because it will make your python experience much more pleasureable. Oh and btw - most of time you dont have to specify the {{ context.something }} call - its enough to call {{ something }}

Modify django templates to check for values in a dict

I have the following Django template.
{% load custom_tags %}
<ul>
{% for key, value in value.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
I need to check for the value and do some modifications.
If the value is True , instead of value I have to print Applied , else if it False I need to print Not Applied.
How to achieve that?
Very simple if-else clause here. Take a look at the django template docs to familiarize yourself with some of the common tags.
{% if value %}
APPLIED
{% else %}
NOT APPLIED
{% endif %}
You asked how to do this as a filter... I'm not sure why, but here is it:
In your app's templatetags directory create a file called my_tags.py or something and make the contents
from django import template
register = template.Library()
#register.filter
def applied(value):
if value:
return 'Applied'
else:
return 'Not applied'
Then in your template make sure to have {% load my_tags %} and use the filter with {{ value|applied }}

Django loop variable as key

i am new to django and tried to use the variable of an loop as a key for another object:
this is my views.py
...
files = Files.objects.filter(dataset__id = instance.dataset.id)
context = {'files': files, 'range': range(files.count())}
return render_to_response("test.html", context, context_instance=RequestContext(request))
and my test.html looks like this:
{% for i in range %}
<img title="{{i}}" src="{{files.i.data_files.url}}"/>
{% endfor %}
if i use files.0.data_files.url (or 1,2,3..) instead of files.i. it works, but i want to give out all images and also need the position of the image.
can you help me please?
the thing you're probably looking for is a magic variable {{ forloop.counter }} (or {{ forloop.counter0 }} if you want to use zero-based index) available inside {% for %} loop:
{% for file in files %}
<img title="{{ forloop.counter }}" src="{{file.data_files.url}}"/>
{% endfor %}

django template filters change order of evaluation

Is there a way to change the order django evaluates a template filter ?
Say i have
{{ 3|add:5|multiply:"10" }}
Right now his adds 3+5 and multiplies the result times 10.
What i am looking for is a way of doing the following:
{{ 3|add:(5|multiply:"10") }}
As you can see i wrapped the 5|multiply:"10" in parenthesis to emphasize that it should be evaluated before the |add. Is this possible ?
You have two possibilities:
You could change the order of filters/values:
{{ 5|multiply:10|add:3 }}
Or You could use {% with %}:
{% with temp=5|multiply:10 %}
{{ 3|add:temp }}
{% endwith %}

Categories

Resources