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

Refresh

1 weeks ago

Views

427 time

1

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

1

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

@register.filter
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.

3

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, [
    model_obj.address_1,
    model_obj.address_2,
    u', '.join(filter(None, [model_obj.address_city, model_obj.state])),
    model_obj.zip,
])


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