Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在基于类的视图中重写GET请求时,如何引用表单?_Python_Django_Django Views - Fatal编程技术网

Python 在基于类的视图中重写GET请求时,如何引用表单?

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

我在这个基于类的视图中重写了GET-request函数处理程序。在else语句中,我需要将类自然创建的表单作为上下文数据传递(如果我没有重写GET函数的话)。我该怎么做

我没有在forms.py创建表单来为Post模型创建表单。我让基于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)

完美的这正是我想要的。