1👍
Show the below values in my django template
Wireless Internet, Air Condition, Wardrobe
The answer I was afraid to give, because it’s not really practical or best practice to save that kind of representation into the database, but since you revealed Room.amenities
is a string:
>>> s = "[u'Wireless Internet', u'Air Condition', u'Wardrobe', u'Television', u'In House Movies', u'Flatscreen TV']"
>>> ', '.join([str(x) for x in eval(s)])
'Wireless Internet, Air Condition, Wardrobe, Television, In House Movies, Flatscreen TV'
The above takes the string representation you have, and gives the string representation you want. Does the job you want but it’s really not recommended. eval()
is dangerous, you can lookup the security implications.
The better way would be to process that when you save the model, so that you don’t need to process this each time you display it (not recommended, but may be necessary if you don’t want to use DB relationships or ArrayField
You have using a MultipleChoiceField
, which gives its result as a list of unicode objects.
So the direct output from that form field is like below an actual list, so let’s not try and turn that into a string in Python.
Keep it as it is, then you can process the format you want
>>> amenities = [u'Wireless Internet', u'Air Condition', u'Wardrobe', u'Television', u'In House Movies', u'Flatscreen TV']
>>> ', '.join([str(x) for x in amenities])
'Wireless Internet, Air Condition, Wardrobe, Television, In House Movies, Flatscreen TV'
Then you can save it to the model
room.amenities = ', '.join([str(x) for x in amenities])
room.save()
Even betters ways to explore (Recommended)
You could use a relationship, you’d have Room
model, then each Room
would have zero, or many RoomAmenity
objects associated with it. read more on Django Relationships.
class Room:
...
amenities = models.ManyToManyField(RoomAmenity)
class RoomAmenity:
name = CharField()
def __unicode__(self): # use __str__ in Python 3
return self.name
Then in template
{% for amenity in room.amenities %}
{{amenity}}
{% endfor %}
You could use ArrayField
and store each amenity as an element in the room.amenities
list field. This is possible on PostgreSQL e.g., see Django docs, it may be possible for the DB you are using too.
Is there a way I can make it display like dis
<li> wireless internet </li> <li> Air Condition </li>
? hope u get my point?
If you’re not ready to use the recommended way to store the amenities as a relation or a list, you can also pull the string representation and parse the items out of it like below:
>>> 'Wireless Internet, Air Condition, Wardrobe'.split(',')
['Wireless Internet', ' Air Condition', ' Wardrobe']
Now you have a list that you can pass to the template and iterate through to display.