首页 > 解决方案 > 如何将基于类的视图转换为基于函数的视图?- 姜戈

问题描述

我正在尝试将所有基于类的视图更改为基于函数的视图,但在转换以下类时遇到了困难:

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView):
    model = Post
    fields = ['image', 'title', 'category', status', 'description']
    template_name = 'blog/post-form.html'
    success_message = 'Your post has been updated.'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

    def get_context_data(self, **kwargs):
        context = super(PostUpdateView, self).get_context_data(**kwargs)
        context['title'] = 'Update post'
        context['submit'] = 'Update'
        return context

    def get_success_url(self):
        author = self.object.author 
        return reverse_lazy( 'profile', kwargs={'author': author.username})

函数和表单应该完全符合这个基于类的视图所做的,所以如果有人可以帮助我,请告诉我。

标签: pythondjangodjango-modelsdjango-formsdjango-views

解决方案


您可以在( 以及)中指定.form_class属性 [Django-doc]。所以我们可以创建一个像这样的表单:UpdateViewCreateView

# app/forms.py

from django import forms

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['image', 'title', 'category', 'status', 'description']
        widgets = {
            'image': …
        }

替换为要用于该image字段的小部件的位置。

然后您可以插入该表单:

# app/views.py

from app.forms import PostForm

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView):
    model = Post
    form_class = PostForm
    template_name = 'blog/post-form.html'
    success_message = 'Your post has been updated.'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

    def get_context_data(self, **kwargs):
        context = super(PostUpdateView, self).get_context_data(**kwargs)
        context['title'] = 'Update post'
        context['submit'] = 'Update'
        return context

    def get_success_url(self):
        author = self.object.author 
        return reverse_lazy( 'profile', kwargs={'author': author.username})

在幕后,如果你不指定 a form_class,Django 会简单地用modelform_factory[Django-doc]为你制作一个,所以通过使用另一个ModelForm,我们不会改变使用表单的逻辑。


推荐阅读