Django模板中无法获取DetailView方法返回的Bargain模型bprice值如何解决
问题原因及解决方案
核心错误原因
- 方法调用缺少必传参数:你定义的
get_bargain方法要求传入request参数,但模板中调用view.get_bargain时没有传递任何参数,导致方法无法正常执行返回空值,自然无法获取bprice属性。 is_authenticated调用错误:Django 1.10及以上版本中,request.user.is_authenticated是布尔属性而非方法,加括号调用is_authenticated()会抛出异常,打断方法执行。- 视图实例不存在
user属性:方法内部打印语句print("this is the user ", self.user.pk)中,DetailView实例本身没有内置的user属性,这行代码会直接抛出属性不存在异常,导致方法终止运行。
修复步骤
1. 修正视图方法
直接从类视图内置的self.request属性获取请求对象,不需要额外传参,同时删掉错误代码:
class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_bargain(self): if self.request.user.is_authenticated: return Bargain.objects.filter(item=self.object, user=self.request.user).first()
2. 优化模板调用
增加非空判断,避免用户无对应砍价记录时模板报错:
{% if view.get_bargain %} <h1>This is the Bprice :{{ view.get_bargain.bprice }}</h1> {% endif %}
内容的提问来源于stack exchange,提问作者Amaeraa Sethi
相关产品推荐
相关产品推荐

