django 使用FormMixin与DetailView?

ghg1uchk  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(132)

详情页:我们要显示表单:根据文档,我们必须使用 Package 器:
from django.views import查看

class CommentGet(DetailView): 
    model = Article
    template_name = "article_detail.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["form"] = CommentForm()
        return context

class CommentPost(SingleObjectMixin, FormView): 
    model = Article
    form_class = CommentForm
    template_name = "article_detail.html"
    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().post(request, *args, **kwargs)
    def form_valid(self, form):
        comment = form.save(commit=False)
        comment.article = self.object
        comment.save()
        return super().form_valid(form)
    def get_success_url(self):
         article = self.get_object()
         return reverse("article_detail", kwargs={"pk": article.pk})
class CView(View):
    def get(self, request, *args, **kwargs):
        view = CommentGet.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = CommentPost.as_view()
        return view(request, *args, **kwargs)

我们是否可以简单地使用post方法与detailview?

class Detail(DetailView):
    model = ... 
    def post(self):
        #do something here.

请帮帮我...

bmp9r5qi

bmp9r5qi1#

不知道,但我经常将SingleObjectMixin添加到FormView,结果非常相似,但使用post方法处理表单。
您必须知道的一件事是,您有责任调用self.object = self.get_object()或以其他方式检索要显示的对象。您可以在get_context_dataform_valid中执行此操作(如果需要处理有效形式,则使用后者,通常情况下)。
Classy class-based views是使用CBV进行子类化和混合的宝贵资源

相关问题