以下是我正在使用的代码:
class FeedView(LoginRequiredMixin, generic.ListView):
template_name = "feed/feed_list.html"
model = Feed
def get(self, request, *args, **kwargs):
response = super(FeedView, self).get(request, *args, **kwargs)
return response
def get_context_data(self, *args, **kwargs):
context = super(FeedView, self).get_context_data(*args, **kwargs)
context["feeds"] = Feed.objects.all()
context["new_feed_form"] = FeedFormSet(queryset = Feed.objects.none())
context["commentform"] = CommentForm()
return context
def post(self, request, *args, **kwargs):
formset = FeedFormSet(request.POST, request.FILES)
if formset.is_valid():
forms = formset.save(commit=False)
for form in forms:
form.name = self.request.user
form.save()
return redirect("feeds")
else:
# THIS WAY
context = self.get_context_data(*args, **kwargs)
# OR THIS WAY
# context = {
# 'feeds' : Feed.objects.all(),
# }
# context["new_feed_form"] = formset
return render(request, self.template_name , context)
在Post
方法中,当表单无效时,按context
设置context = self.get_context_data(*args, **kwargs)
变量会给出错误'FeedView' object has no attribute 'object_list'
。然而,再次设置它们(如下所示'或者这个方式和代码中的#39;)工作正常。如何通过context
设置context = self.get_context_data(*args, **kwargs)
变量时修复错误?