我尝试在详细视图中添加或覆盖一些上下文值。 但是结果不会显示在页面上,任何想法怎么可能??
最新的Django版本。
id和数量是模型的一部分。 金额应被覆盖并应加醉酒。
class EntryDetailView(DetailView):
context_object_name = 'entry'
model = models.Entry
template_name = 'web/entry_detail.html'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['amount'] = "what shall we do with the drunken sailer"
context['drunk'] = "so drunken"
return context
模板包含:
<div class="jumbotron">
id : {{ entry.id }} <br>
amount: {{ entry.amount }}<br>
drunk: {{ entry.drunk }}<br>
</div>
我明白了:
id : 1
amount: 5
drunk:
虽然我期望
id : 1
amount: what shall we do with the drunken sailer
drunk: so drunken
答案 0 :(得分:0)
您没有覆盖实体的密钥。 context
不不包含项id
,amount
和drunk
。它包含一个键'entry'
,该键映射到获取的Entry
对象,并具有属性amount
和drunk
。
您可以覆盖这些属性,例如:
class EntryDetailView(DetailView):
context_object_name = 'entry'
model = models.Entry
template_name = 'web/entry_detail.html'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
entry = context['entry']
entry.amount = 'what shall we do with the drunken sailer'
entry.drunk = 'so drunken'
return context
但是,覆盖模型对象的属性通常不是一个好主意。
使用 old 上下文,您可以将数据呈现为:
<div class="jumbotron">
id : {{ entry.id }} <br>
amount: {{ amount }}<br>
drunk: {{ drunk }}<br>
</div>
答案 1 :(得分:0)
的确如此,我在手册中误导了我的内容,在此处以https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-simple/为例