I have a users click a series of checkboxes to identify which areas a certain place is related to (i.e, entertainment, sports etc) , which I then retrieve with:
areas_related=request.POST.getlist('areas_related')
When I am displaying those values in a different view of what areas different places are related to I am using:
{% for service in services %}
{{service.areas_related}}
{% endfor %}
… But it is displayed as:
[u'Education', u'Food']
.. If I try to make a for loop to go through the list, each individual character gets displayed, one line at a time. I.e.,
[
u
‘
E
etc.Is there a filter I can use to not display [u’, etc.?
Any help would be appreciated.
What is probably going on here is that you are storing the
areas_relatedas a string.So you probably have a model like:
and then in the view you do this:
So what is going on here is that
request.POST.getlist('areas_related')returns a Python list. However then you store that value into a string field of your model. As a result, Django tries to convert the given list to a string, which it then stores in the db; and when you convert Python list to a string, the result is a string representation of the list:To solve this, you can do one of these things:
Foreign Key
Instead of storing all the
areas_relatedas a single field within your model, store those as foreign keys. This I think is a better way because then you can do SQL aggregation and is just considered more flexible compared to the next method.Encoded string
Store the list in the
areas_relatedmodel field as a string by encoding it somehow, and then on retrieval decode to get the list. This method is nice because everything gets stored in db in one column, however then you can’t really do any queries on theareas_relatedbecause it will store an encoded string of multiple values instead of just one.