Python 在基于类的视图中重写GET请求时,如何引用表单?
我在这个基于类的视图中重写了GET-request函数处理程序。在else语句中,我需要将类自然创建的表单作为上下文数据传递(如果我没有重写GET函数的话)。我该怎么做 我没有在forms.py创建表单来为Post模型创建表单。我让基于create类的视图为我处理表单创建。那么,我如何获得这个表单并作为上下文数据传递呢 我能想到的唯一方法就是创建一个基于函数的视图,避免在这种情况下使用这个基于类的视图Python 在基于类的视图中重写GET请求时,如何引用表单?,python,django,django-views,Python,Django,Django Views,我在这个基于类的视图中重写了GET-request函数处理程序。在else语句中,我需要将类自然创建的表单作为上下文数据传递(如果我没有重写GET函数的话)。我该怎么做 我没有在forms.py创建表单来为Post模型创建表单。我让基于create类的视图为我处理表单创建。那么,我如何获得这个表单并作为上下文数据传递呢 我能想到的唯一方法就是创建一个基于函数的视图,避免在这种情况下使用这个基于类的视图 class PostCreateView(LoginRequiredMixin, Create
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})
您可以使用类提供的方法,即
self.get\u 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)
完美的这正是我想要的。