在Django中将FormMixin添加到DetailView

时间:2018-08-29 14:29:08

标签: django django-forms django-views

我想向通用的“详细信息”视图添加一个表单。 Official documentation表示这是个坏主意,基本上建议这样做:

from django import forms
from django.views.generic import DetailView
from books.models import Author

class AuthorInterestForm(forms.Form):
    message = forms.CharField()

class AuthorDisplay(DetailView):
    model = Author

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = AuthorInterestForm()
        return context

和:

from django.http import HttpResponseForbidden
from django.urls import reverse
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin

class AuthorInterest(SingleObjectMixin, FormView):
    template_name = 'books/author_detail.html'
    form_class = AuthorInterestForm
    model = Author

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden()
        self.object = self.get_object()
        return super().post(request, *args, **kwargs)

    def get_success_url(self):
        return reverse('author-detail', kwargs={'pk': self.object.pk})

简而言之,为了避免执行不同功能的同名函数之间发生冲突,最佳实践是将表格拆分并将其显示为两个部分。没关系但是我不知道如何调用适当的视图?从下面的排序选择视图?如何在网址中定义它?

整个想法是拥有一个模板,该模板将在上下文中接收对象,并且与->无关,从而应加快提交将POST返回到同一视图。如果我必须从urls.py中选择get()或post(),那不是我想要的。

from django.views import View

class AuthorDetail(View):

    def get(self, request, *args, **kwargs):
        view = AuthorDisplay.as_view()
        return view(request, *args, **kwargs)

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

TNX

0 个答案:

没有答案