如何迭代模型实例? Django的

时间:2015-10-22 20:03:30

标签: python django

我正在尝试迭代模型实例。 我想得到这个: TITLE1 TITLE2

我真正得到了什么 TITLE1 TITLE1 TITLE1 TITLE1 TITLE1 TITLE1

什么似乎是问题?

view.py

from django.shortcuts import get_object_or_404,

from .models import Paper 

def detail(request, slug):
    paper = get_object_or_404(Paper, slug=slug)
    return render(request, 'papers/detail.html', {'paper': paper})

models.py

from django.db import models
from django.template.defaultfilters import slugify

class Paper(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    description = models.CharField(max_length=300)


    def __str__(self):
       return self.title

    def save_in(self):
        if not self.id:
            self.slug = slugify(self.title)

        super(test, self).save()

detail.html

{% extends "master2.html"  %}

{% block h1 %}
    <div id="g">
        <div class="container">
            <div class="row">
                <h3>{{ paper.title }}</h3> 
                <br>
                <br>
                 <div class="col-xs-12 "><p>{{ paper.large_description }}</p></div>
            </div>
        </div>
     </div>
{% endblock %}

{% block title  %} Detail {% endblock %}

nav.html

            {% for title in paper.title %}
                <a href="{% url 'detail' slug=paper.slug %}">{{ paper.title }}</a>
            {% endfor %}

master2.html

<!DOCTYPE html>
<html>
    <head>
        <title>{% block title %}{% endblock %}</title>
        <link href="/static/font.min.css" rel="stylesheet">
        <link href="/static/bootstrap.min.css" rel="stylesheet">
        <link href="/static/font-awesome.min.css "rel="stylesheet">
        <link href="/static/main.css" rel="stylesheet">
    </head>        
    <body data-spy="scroll" data-offset="0" data-target="#theMenu"> 
        {% include "nav.html" %}           
        {% include "header2.html" %}
        {% block h1 %}{% endblock %}
    <script src="/static/jquery.js"></script>
    <script src="/static/bootstrap.min.js"></script>
    <script src="/static/jquery.isotope.min.js"></script>
    <script src="/static/jquery.prettyPhoto.js"></script>
    <script src="/static/main2.js"></script>
</body>

1 个答案:

答案 0 :(得分:1)

当你这样做时

{% for title in paper.title %} <!-- Im assuming you already have a
                                    {% for paper in paper_list %} statement 
                                    because a "paper" variable is not even
                                    passed to the template, "paper_list" was
                                    passed to the template. -->

    <a href="{% url 'detail' slug=paper.slug %}">{{ paper.title }}</a>
{% endfor %}

您正在迭代CharField(paper.title是CharField)。然后对于paper.title中的每个字母,您将显示标题,这就是您始终只获得title1的原因。要迭代所有Paper对象,然后显示每个纸质对象的标题,请执行以下操作:

{% for paper in paper_list %}
     <a href="{% url 'detail' slug=paper.slug %}">{{ paper.title }}</a>
 {% endfor %}