简体   繁体   English

将变量传递给 django 中的模板

[英]Pass variable in to template in django

Can anyone help me to solve my Problem, I'm trying to pass a variable from my view to my Template.谁能帮我解决我的问题,我正在尝试将变量从我的视图传递到我的模板。 But the variable does not show up when I load my the site.但是当我加载我的网站时,变量没有显示出来。

Model: Model:

class Artikl(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
category = models.CharField(max_length=60)
price = models.PositiveIntegerField()
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.name

Views:意见:

from django.shortcuts import render
from .models import Artikl

def home(request):

    context = {
        'artikl': Artikl.objects.all()
    }

    return render(request, 'base/home2.html', context)

Template:模板:

    {% for artikl in Artikl %}
    <div class="row g-4">
        <div class="col-md-6 col-lg-3">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <img src="https://picsum.photos/300/200" class="mb-3 img-fluid" alt="">
                
                    <h3 class="card-title mb-3">{{ artikl.name }}</h3>
                    <p class="card-text">{{ artikl.description }}</p>
                    
                    <button type="button" class="btn btn-primary">Kupi</button>
                </div>
            </div>
        </div> 
        {%endfor%}

Try this,尝试这个,

in template, you're not referring to the context you're passing在模板中,您不是指您传递的上下文

from django.shortcuts import render
from .models import Artikl

def home(request):

    context = {
        'Artikl': Artikl.objects.all()
    }

    return render(request, 'base/home2.html', context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM