Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django for loop in a .html template page (newbie)

The thing I really hate when learning a new language / framework is how ignorant I feel when I get stuck on a seemingly easy to solve issue.

I have a django for loop inside a html page but for some reason it is not working. I have missed something and cannot fix the issue on my own, so I turn to StackOverflow to help me.

This is my model I am running my query on models.py:

class RIAchievement(models.Model):
  riAchievementID = models.AutoField(primary_key=True, db_column="RIAchievementID")
  userLanguageVersionID = models.ForeignKey(UserLanguageVersion, db_column="UserLanguageVersionID")
  typeAchievementID = models.ForeignKey(TypeAchievement, db_column="TypeAchievementID")
  riAchievementTypeUserDescription = models.CharField(max_length=255, blank=True, null=True, db_column="RIAchievementTypeUserDescription")
  riAchievementDescription = models.TextField(max_length=2000, db_column="RIAchievementDescription")
  auth_user_id = models.ForeignKey(auth_user, db_column="auth_user_id")
  class Meta:
    db_table="RIAchievement"

This is where my models.py file is located in my project: GlobalXpy\app_data\models.py

This is the code within my views.py file:

from django.shortcuts import render_to_response
from GlobalXpy.app_data.models import RIAchievement

def index(request):
  ri_achievement = RIAchievement.objects.all()
  get_template = loader.get_template('ri_achievement.html')
  return render_to_response(get_template)

This is the for loop that is inside my template file (ri_achievement.html):

{% for e in ri_achievement %}
  <td> Preview  Edit  Duplicate  Delete </td>
  <td> FlagPath </td>
  <td> AchievementType / RIAchievementTypeUserDescription </td>
  <td> {{ e.riAchievementDescription }} </td>
{% endfor %}

Any assistance would be appreciated.

like image 804
user1261774 Avatar asked Apr 26 '12 01:04

user1261774


2 Answers

from django.shortcuts import render
from GlobalXpy.app_data.models import RIAchievement

def index(request):
  ri_achievement = RIAchievement.objects.all()
  return render(request, 'ri_achievement.html',{'ri_achievement': ri_achievement})

In your template:

{% if ri_achievement %}
   There are {{ ri_achievement|length }} records:
   {% for e in ri_achievement %}
      <td> Preview  Edit  Duplicate  Delete </td>
      <td> FlagPath </td>
      <td> AchievementType / RIAchievementTypeUserDescription </td>
      <td> {{ e.riAchievementDescription }} </td>
   {% endfor %}
{% else %}
   There are no records in the system
{% endif %}
like image 159
Burhan Khalid Avatar answered Oct 18 '22 10:10

Burhan Khalid


You forgot to pass the variable.

return render_to_response(get_template, {'ri_achievement': ri_achievement})
like image 45
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 10:10

Ignacio Vazquez-Abrams