Reputation: 1479
I'm new to django and am having trouble reading data from a model in a template.
Here's the model.
class Team(models.Model):
team_name = models.CharField(max_length=30, default="Team")
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.team_name
The view.
def create_team(request):
team = Team.objects.all()
return render_to_response("ideas/profile.html", {'team':team})
And the template.
<h2>Available groups: {{team.team_name}} </h2>
Likelihood this is an obvious fix: 99%. Thanks anyway guys!
Upvotes: 2
Views: 946
Reputation: 239440
team
is not an object, it's a queryset -- simplistically, a list of objects. Even if there's only one object in the table, it's simply a list of one. As a result, you can't just reference model attributes on it as if it were an instance of the model -- you have to pull the instance out first:
{% for t in team %}
{{ t.team_name }}
{% endfor %}
A couple of notes. As the loop shows, naming it team
doesn't make sense. That implies one thing, and now we're going to loop through a single entity? Best practice here is to name single items singular and querysets, lists, etc. plural. Then we would do for team in teams
which makes a lot more sense.
Secondly, don't use the model name in the attribute name. team.team_name
is redundant, when team.name
would work just as well. If there's another "name" attribute, then prefix that one, but the model itself should have priority on top-level attribute names.
Upvotes: 2