Search code examples
djangotemplatetags

How to correctly unpack tuple and display it?


I have ['34242342', 'Ford focus 2015', 'Chevrolet Impala 1960', 'Ford focus 2012', 'Dodge charger 2010', 'Dodge', 'New fiat punto 2012'] created from: (('34242342',), ('Ford focus 2015',), ('Chevrolet Impala 1960',))(not full).

And I want to display it on my template:

{% for p in full %}
 <form action="{% url 'table' %}" method="GET">

  <input style="background-color:#2F4050;color:#A7B1C2; margin-top:5px;border: none; border-color: rgba(0,0,0,0.9);" type="submit" value={{ p }} name="button">
    </form>
{% endfor %}

But instead of displaying full elements it cuts it:

34242342
Ford
Chevrolet
Ford
Dodge
New

It displays everything correctly if I call elements like:

{% for p in full %}
{{p}}
{% endfor %}

It cuts elements only in value option of input.

UPDATED

views.py:

db = MySQLdb.connect(host="192.168.4.200",
                         user="root",
                         passwd="123456",
                         db="store", charset="utf8")
cur = db.cursor()

cur.callproc('store')

info = cur.fetchall()
full = info
new_list = []
for tup in full:
    full = ",".join(tup)

    new_list.append(full)

return render(request, 'table.html', {'full': new_list})

Simple request to database and displaying data.


Solution

  • You can unpack the tuple of 1-tuples with list comprehension:

    data = (('34242342',), ('Ford focus 2015',), ('Chevrolet Impala 1960',))
    result = [item for item, in data]
    

    For example:

    >>> [item for item, in data]
    ['34242342', 'Ford focus 2015', 'Chevrolet Impala 1960']
    

    Note the comma in item, this forces the unpacking of the 1-tuple.

    If the tuples can contain more elements, you can loop over these as well:

    result = [subitem for item in data for subitem in item]
    

    That being said, please do not use .values_list(..) to retrieve data. Retrieve the model objects. Such that the logic implemented in the model is retained. It is furthermore strongly advisable to use the Django ORM. Django's models are often what makes Django effective to work with.

    In the template you should use quotes for the attribute:

    <input value="{{ p }}" name="button"<