Home > Mobile >  Pass variable in to template in django
Pass variable in to template in django

Time:07-03

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:

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 >
        <div >
            <div >
                <div >
                    <img src="https://picsum.photos/300/200"  alt="">
                
                    <h3 >{{ artikl.name }}</h3>
                    <p >{{ artikl.description }}</p>
                    
                    <button type="button" >Kupi</button>
                </div>
            </div>
        </div> 
        {%endfor%}

CodePudding user response:

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)
  • Related