简体   繁体   中英

Looping in django template with variable parameter

I want to get all the details of class Material where user=user_id Here is the models.py:

class Material(models.Model):
    subject = models.CharField(max_length=10)
    topic = models.CharField(max_length=50)
    user = models.IntegerField()

and my views.py:

def add_material(request):
    c = {}
    c.update(csrf(request))
    if 'user_session' in request.session:
        user_id = request.session['user_session']
        material_array = Material.objects.filter(user=user_id).values()
        materials_len = len(material_array)
        c['m_len'] = materials_len
        for i in range(0, materials_len):
            c['material_id_'+str(i)] = material_array[i]
        return render_to_response('add_material.html',c)
    else:
        return HttpResponseRedirect('/user')

and my add_material.html is:

{% for i in range(m_len) %}
    <tr>
    {% for j in material_id_+str(i) %}
        {{j.subject}}
        {{j.topic}}
    {% endfor %}
    </tr>
{%endfor%}

So I am getting error in template, how to insert variable in for loop?

This how I would do it.

views.py

def add_material(request):
    c = {}
    c.update(csrf(request))
    if 'user_session' in request.session:
        user_id = request.session['user_session']
        material_array = Material.objects.filter(user=user_id)
        c.update({'materials': material_array})
        return render_to_response('add_material.html', c)
    else:
        return HttpResponseRedirect('/user')

template

{% for material in materials %}
    <tr>
        <td>{{ material.subject }}</td>
        <td>{{ material.topic }}</td>
        <td>{{ material.user.username }}</td>
    </tr>
{% endfor %}

You can include any user field you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM