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

Question:

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/>
Asked By: Shehzad009

||

Answers:

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…

Answered By: FallenAngel

Use the built-in default_if_none filter.

{{ client.user|default_if_none:"&nbsp;" }}
{{ client.user|default_if_none:"" }}
Answered By: Chris Morgan

this is such a strange problem.
I have a good idea for it. If you want to modify your field at display time than rather checking it at template , check it at your model class.

ExampleModel(models.Model):
    myfield = models.CharField(blank=True, null = True)

    @property
    def get_myfield(self)
        if self.myfield:
              return self.myfield
        else:
              return ""

Use it in your template directly instead of field.

 {{ExampleModel.get_myfield}}

you never need to change your template to change this field in future, just modify you property.

Answered By: Manoj Sahu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.