Django: How to nicely format an address in a template without knowing how much information is available?


February 2019


430 time


I have a table with address information. It has these fields.

  • address_1
  • address_2
  • city
  • state
  • zip

No field is required. I want to display this in a template and format it nicely. I want line breaks between address_1, address_2, and the city/state/zip line for any of those that exists. I also want a comma between city and state if both exist. What is the best way to accomplish this? I started writing an if statement in the template, but it seemed to be getting a bit unwieldy. The big problem is that the user could enter only a city and state, only a zip code, a full-formed address, or anything between.

2 answers


If you add a simple custom filter to append text to variables if they exist:

def append(arg, suffix):
    return arg + suffix if arg else ''

then you can do something like

{{ address_1|append:"<br/>" }}
{{ address_2|append:"<br/>" }}
{{ city|append:", " }}{{ state|append:" " }}{{ zip }}

If you want to do this in a <table> or whatever, you can also use a similar prepend filter.


Many ways of achieving this, none are likely to be that elegant. I'll throw this into the ring... Do this in your handler, and pass address_parts to the template context.

## Gather the address components in groups, removing any that are None
address_parts = filter(None, [
    u', '.join(filter(None, [model_obj.address_city, model_obj.state])),,

## In the template, join the address groups
{{ address_parts|join:"<br>" }}