我在基于此类的视图中覆盖了GET请求函数处理程序。在我的else语句中,我需要传递该类自然创建的形式作为上下文数据(如果没有覆盖GET函数)。我该怎么办?
我没有在forms.py中创建表单来为Post模型创建表单。我让基于创建类的视图为我处理表单创建。因此,我如何获得此表单并作为上下文数据传递。
我想到的唯一方法是创建基于函数的视图,并避免在这种情况下使用基于类的视图。
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ["title", "content", "payment_option", "price"]
def get(self, request):
card_set = BillingProfile.objects.get(user=request.user).card_set.all()
if not card_set.exists():
# The user does NOT have an inserted payment method.
return redirect("/billing/payment-method?next=/post/new/")
else:
# The user DOES have an inserted payment method.
form = "???"
return render(request, "posting/post_form.html", {"form":form})
答案 0 :(得分:1)
您可以使用类提供的方法,即self.get_form()
。
但这实际上不是正确的选择。您真正应该做的是将get
的默认实现委派给默认实现,然后让它执行通常会执行的操作。
if not card_set.exists():
# The user does NOT have an inserted payment method.
return redirect("/billing/payment-method?next=/post/new/")
else:
return super().get(request)