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

一笑奈何 提交于 2021-02-18 08:53:46

问题


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

回答1:


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




回答2:


Use the built-in default_if_none filter.

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



回答3:


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.



来源:https://stackoverflow.com/questions/6584235/django-want-to-display-an-empty-field-as-blank-rather-displaying-none

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!