【发布时间】:2013-11-28 00:49:55
【问题描述】:
我在模型中有一个 Product 对象,
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=255, unique = True)
description = models.TextField()
image_url = models.URLField(verify_exists=True, max_length=200, blank = True, null = True)
quantity = models.PositiveSmallIntegerField(default=0)
def sell(self, save=True):
self.quantity -= 1
if save:
self.save()
还有一个名为:product_view.html Product {{product.title}} 的模板
和一个名为:product_list.html {% for p in products %}{{p.id}},{% endfor %}
我想让视图从数据库中检索 Product 对象,使用它来呈现模板,最后返回一个包含结果字符串的 HttpResponse 对象。如果找不到具有给定 product_id 的产品,则引发 404 异常(或返回 HttpResponseNotFound)
def productview(request, product_id):
"""
I dont know how to write here
"""
#render template "product_view.html" with param product
return HttpResponse("product %s" % product_id)
同时,如果我想呈现一个包含所有可用产品列表的页面。如果产品的数量大于 0,则该产品可用。模板 product_list.html 期望上下文中的单个参数 products 引用 Product 对象的可迭代。
那么如何让视图检索可用的产品以及如何使用它们来呈现模板并返回包含结果字符串的 HttpResponse 对象?
def available_products(request):
"""
I dont know how to write here
"""
#render template "product_list.html" with param products
return HttpResponse("View not implemented!")
非常感谢
【问题讨论】:
-
是渲染模板还是返回字符串?
-
有趣的是,我正在解决与您完全相同的家庭作业:) 只是应该不是“我不知道如何在这里写”,而是应该:“””编写您的视图实现以进行练习4 这里。去掉下面的当前返回行。"""
标签: django django-views