1

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?

asked May 24, 2015 at 11:36
4
  • What are you trying to do? Loop all users and all materials for each user? Commented May 24, 2015 at 11:42
  • 1
    You should add all of those items to a single materials list. That way, you won't need to do any of this. Commented May 24, 2015 at 11:47
  • @Wtower actually i want to list of materials with details for a given user Commented May 24, 2015 at 11:53
  • @mevius how can we do this? Commented May 24, 2015 at 11:54

1 Answer 1

4

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.

answered May 24, 2015 at 12:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.