Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Want to display an empty field as blank rather displaying None

I have a template called client_details.html that displays user, note and datetime. Now sometimes, a client may not have an entry for user, note and datetime. What my program will do instead is display None if these fields are empty. I do not want the to display None. If a field has no value I don't want to see any value e.g. let it be blank if possible instead of displaying None.

views.py

@login_required def get_client(request, client_id = 0):     client = None     try:         client = models.Client.objects.get(pk = client_id)     except:         pass     return render_to_response('client_details.html', {'client':client}, context_instance = RequestContext(request)) 

template

{{client.datetime}}<br/>  {{client.datetime.time}}<br/>   {{client.user}}<br/> {{client.note}}<br/> 
like image 316
Shehzad009 Avatar asked Jul 05 '11 14:07

Shehzad009


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

How do I check if a field is empty in Django?

Unless you set null=True as well, your database should complain if you tried to enter a blank value. If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None .


2 Answers

Use the built-in default_if_none filter.

{{ client.user|default_if_none:"&nbsp;" }} {{ client.user|default_if_none:"" }} 
like image 184
Chris Morgan Avatar answered Sep 28 '22 08:09

Chris Morgan


you may use:

{% if client %} {{client.user}} {% else %} &nbsp; {% endif %} 

Checking with an if is enough, so you may not user else block if you want...

like image 39
FallenAngel Avatar answered Sep 28 '22 10:09

FallenAngel