python - 如何将基于类的视图转换为基于函数的视图?- 姜戈
问题描述
我正在尝试将所有基于类的视图更改为基于函数的视图,但在转换以下类时遇到了困难:
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})
函数和表单应该完全符合这个基于类的视图所做的,所以如果有人可以帮助我,请告诉我。
解决方案
您可以在( 以及)中指定.form_class
属性 [Django-doc]。所以我们可以创建一个像这样的表单:UpdateView
CreateView
# 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
,我们不会改变使用表单的逻辑。
推荐阅读
- git - 将项目添加到 Git 后 Eclipse/STS Tools 项目资源管理器字体非常小
- c++ - '<' 无法解决类模板中的函数重载和参数不匹配问题,Visual Studio 编译器
- spring-boot - Gradle BOM 项目
- c# - 如何在 COM 事件源和处理程序中指定“事件类型”?
- python - 闰年while循环
- kotlin - 对象中的泛型
- flutter - 升级后:flutter_google_places - 自动完成不显示推荐列表
- java - 启动层初始化时出错 java.lang.module.FindException: Module SimpleJavaProgram not found
- node.js - 使用 blob http 在 node.js 中进行音频流式传输,与自然阅读器在读取 pdf 音频时的方式相同
- amazon-cloudformation - 了解 AWS CodePipeline 中的 CloudFormationStackSet 和 CloudFormationStackInstances 操作