Thursday, October 26, 2017

MultipleChoiceField records down choices as a list, but CharField converts them to a list?

I have a model field for choosing multiple options.  Here is the code for models and forms:

models.py:
    CONDO_APARTMENT = 'Condo Apartment'
    DETACHED_HOUSE = 'Detached House'
    SEMI_DETACHED = 'Semi-detached'
    TOWNHOUSE = 'Townhouse'
    
    PROPERTY_TYPE = (
        (CONDO_APARTMENT, 'Condo Apartment'),
        (DETACHED_HOUSE, 'Detached House'),
        (SEMI_DETACHED, 'Semi-detached'),
        (TOWNHOUSE, 'Townhouse'),
    )

    property_type = models.CharField(max_length=50, help_text="You can select more than 1 option")


forms.py:
    property_type = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=BuyerListing.PROPERTY_TYPE)


Let's assume the selected choices were 'Condo Apartment' and 'Semi-detached'.  The value stored on my database is this - ['Condo Apartment', 'Semi-detached']

Now this is in a list format, which makes sense, but it seems to have been converted to a string.  When I try to call on property_type in a .html document...

{% for property in model.property_type %}
    <p>{{ property }}</p>
{% endfor %}

The result is displayed in singular characters, like this:

[
'
C
o
n
d
o
 
a
p
.. and so on.  Instead I want the result to be the values in the list, like this:

Condo apartment
Semi-detached

How do I do this?  I tried experimenting with different model field types but CharField seems like the only appropriate one for MultipleChoiceField.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/06ff88b7-4ec4-4ddc-a4da-af8e25e3c516%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment