我想将get方法添加到我的DetailView中,但是它不起作用。添加get方法后,我将断开与模板上数据的连接。
#I tried to change {{ object.field_name }} to
#{{ post.field_name }}
#{{ object_list.field_name }}
# in app views I write :
class PostDetailView(DetailView):
model = Post
# in templates I write:
<a>{{ object.author }}</a>
# data is send to templates and it works fine
# But then I want to add a get/post to the view:
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
def get(self, request, *args, **kwargs):
form = HomeForm()
return render(request, self.template_name, {'form':form})
# Once I add the get method , data is not rendering on my template.
如果我将get方法添加到DetailView后,如果有人可以帮助我弄清楚为什么数据无法在模板中呈现,那将很棒。我花了整个下午/晚上进行搜索,但是现在我的大脑已经炸了...帮助,请。 tx tx!
答案 0 :(得分:2)
您正在更改上下文数据,并且在更改的上下文数据中没有对象。您可以删除get方法并添加get_context_data
,这样您的正确代码将如下所示:
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
form = HomeForm()
context['form'] = form
return context