开发者

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, clie开发者_如何学JAVAnt_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/>


Use the built-in default_if_none filter.

{{ client.user|default_if_none:"&nbsp;" }}
{{ client.user|default_if_none:"" }}


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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜