开发者

How do I retrieve timedate from the database and display in template?

I'm a complete Python and Django noob so any help is appreciated. This is what my model looks like:

class Matches(models.Model):
    id = models.AutoField(primary_key=True)
    date = models.DateTimeField()
    court = models.ForeignKey(Courts)

class Participants(models.Model):
    id = models.AutoField(primary_key=True)
    match = models.ForeignKey(Matches)
    userid = models.ForeignKey(User)
    games_won = models.IntegerField()

This is what my view looks like:

def index(request):
    latest_matches_list = Matches.objects.all()[:5]
    return render_to_response('squash/index.html', {'latest_matches_list': latest_matches_list})
    return HttpResponse(output)

And my template:

{% if latest_matches_list %}
    {% for matches in latest_matches_list %}
        {{ match.id }}
    {% endfor %}
{% else %}
    <p>No matches are available.</p>
{% endif %}

Two questions:

  • When I do Matches.objects.all() in the shell console it returns: [<Matches: Matches object>]. Why doesn't it print out the id and date?
  • In the template file I'm initially trying to test printing out the id of Matches but it doesn't seem to be working. What variable do I need for {{ match.id }}. The goal is to print out the following per match:
  • [matchid]开发者_高级运维    [date]    [time]     [player1_wins]  [player2_wins]
    1            1-1-2011  20:00      6            8
    


    1: how would it know to print id and date out of all fields you might have?

    You can define what your object returns when printed by defining __unicode__
    http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.unicode

    # ... model class
    
    def __unicode__(self):
        return "%s %s" % (self.id, self.date)
    

    2: In your template, you iterate over latest_matches_list with the variable matches yet you use {{ match.id }} which isn't defined. Use {{ matches.id }}.

    {% for matches in latest_matches_list %}
        {{ match.id }} <!-- not defined -->
        {{ matches.id }} <!-- this is your variable -->
    {% endfor %}
    
    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新问答

    问答排行榜