使用Django在程序中未检测到模板代码

时间:2015-04-30 05:20:22

标签: python django

我想在我的主页上制作一个滑块,但是当我尝试它时,我无法使它工作。

model.py

class Static(models.Model):
    title           = models.CharField(max_length=50)
    description     = models.TextField()
    images1         = models.ImageField(upload_to="slider")
    images2         = models.ImageField(upload_to="slider")

    def __str__(self):
        return self.title;

view.py

def slider(request):
    slider = Static.objects.all()
    return render(request, 'kerajinan/home.html', {
        'slider' : slider,
    })

admin.py

admin.site.register(Static)

模板 home.html

<div class="carousel-inner">
    {% for i in slider %}
        <div class="item active">
            <div class="col-sm-6">
                <h2>{{i.title}}</h2>
                <p>{{i.description}}</p>
                <button type="button" class="btn btn-default get">Get it now</button>
            </div>
            <div class="col-sm-6">
                <img src="{{i.image1.url}}" class="girl img-responsive" alt="" />
                <img src="{{i.image2.url}}"  class="pricing" alt="" />
            </div>
         </div>
     {% endfor %}
</div>

在代码<div class="carousel-inner">下方,此程序中未读取该内容。

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您可能需要定义一个获取图片网址的操作,但请先尝试更改您的html模板。您拥有的值与您的模型不匹配。您有image1而不是images1它应该是:

<div class="col-sm-6">
    <img src="{{i.images1.url}}" class="girl img-responsive" alt="" />
    <img src="{{i.images2.url}}" class="pricing" alt="" />
</div>

- - - 编辑:

您需要定义一个函数,该函数将在html文件中调用时返回图像URL。截至目前,{{ i.images1.url }}没有返回正确的值,因为url未定义。

试试这个:

模型:

class Static(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField()
    images1 = models.ImageField(upload_to="slider")
    images2 = models.ImageField(upload_to="slider")

    def __str__(self):
        return self.title;

    def get_images1_url(self):
        return "%s/%s" %(settings.MEDIA_URL, self.images1)

    def get_images2_url(self):
        return "%s/%s" %(settings.MEDIA_URL, self.images2)

HTML:

<div class="carousel-inner">
    {% for i in slider %}
        <div class="item active">
            <div class="col-sm-6">
                <h2>{{i.title}}</h2>
                <p>{{i.description}}</p>
                <button type="button" class="btn btn-default get">Get it now</button>
            </div>
            <div class="col-sm-6">
                <img src="{{ i.get_images1_url }}" class="girl img-responsive" alt="" />
                <img src="{{ i.get_images2_url }}"  class="pricing" alt="" />
            </div>
         </div>
     {% endfor %}
</div>

设置:

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), #"First directory", "Second directory", etc, if applicable)