Reputation: 39
I'm trying to use render(request,'sell.thml',context) in django 1.9, I use mysql to be my database. but nothing show up in my template. I don't know why I cannot use render to pass my context variable to template. Anyone can help me about it?
In my view.py:
def sellmainpage(request):
products=Product.objects.all()
context = {
"products": products,
}
return render(request, "sell.html", context)
In my sell.html:
<div class="col-md-8 col-md-offset-2 col-sm-12 maincontent" style="padding-top:100px">
<div class="storefront_product_display" >
{% for product in products %}
<a href="{% url 'product_detail' %}">
<img src="{% static 'img/logo.png' %}">
<span class="storefront_product_name">{{ product.product }}</span>
<span class="storefront_product_companyname">{{ product.company }} </span>
{% endfor %}
</div>
</div>
in my models.py:
class Product(models.Model):
product=models.CharField(max_length=200)
company=models.ForeignKey(Company)
description=models.TextField()
price=models.DecimalField(decimal_places=2,max_digits=10)
stock=models.IntegerField(default=0)
def __str__(self):
return self.product
Upvotes: 0
Views: 4902
Reputation: 460
instead of
return render(request, "sell.html", context)
try
loader.get_template('sell.html')
return HttpResponse(template.render(context,request))
don't forget to import needed things.
from django.template import loader
from django.http import HttpResponse
Upvotes: 0
Reputation: 86
Show us your setting, you should have a folder "template", and inside the html
Example settings.py
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'template'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'trabajo.context_processors.globales',
'trabajo.context_processors.menu',
'trabajo.context_processors.globales',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.static',
],
},
},
]
you view.py:
def sellmainpage(request):
products=Product.objects.all()
context = {
"products": products,
}
template = "template/sell.html"
render_to_response(template,context,context_instance=RequestContext(request))
sell.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Upvotes: 1