我正在使用 wagtail 开发博客应用。
关于博客页面的要点: 作家可以写“标题”、“介绍”和“正文”。 首先,作者可以提交标题。 完成“标题任务”后,作者可以编辑和提交正文。 作者做标题任务时,作者不能编辑正文字段。 此外,作者在做 body 任务时,作者不能编辑标题字段。
我想动态更改 titleField
和 bodyField(RichTextField)
的权限,但我不知道该怎么做。
我以为编辑wagtail_hooks.py中关于@hooks.register("after_edit_page")
的钩子(Hook)可以解决。
我尝试使用 PagePermissionHelper
、PermissionHelper
。
最佳答案
建议的解决方案
- 关于 Customising generated forms 的 Wagtail 文档解释了覆盖在编辑/创建新页面时生成的表单的方法。
WagtailAdminPageForm
扩展了 DjangoModelForm
,您可以进一步扩展它以添加自定义clean
/__init__
/save
等方法,基本上可以将您想要的任何逻辑添加到表单呈现方式以及在应用保存之前向用户提供哪些错误。- Django ModelForm documentation .
- 默认情况下,您无法访问表单创建时的
request
对象,但您可以通过save
方法获取它,因此可以轻松地执行一些操作那里的用户基本逻辑。 - 如果您需要进一步定制,可以深入研究 Wagtail edit handers (搜索源代码),您可以创建自己的编辑处理程序,将请求传递给您的自定义
BlogPageForm
。 - 注意:如果最终目标是添加基于“流程”的完整页面编辑工作流程,您可能需要查看 Wagtails 的
ModelAdmin
基本上只是完全独立于正常页面结构构建博客工作流程,然后重组权限,以便博客编辑者无法访问正常页面树,而只能访问您的自定义工作流程。
示例代码
- 这只是
BlogPage
模型的自定义表单的一个基本示例。 __init__
可以扩展以将自定义逻辑添加到如何生成表单(例如,使某些字段只读或什至“隐藏”某些字段)。save
可以扩展以将服务器端验证添加到只读字段,并提供面向用户的错误消息。- 通过检查 self.instance.pk(主键)是否存在,可以添加"new"页面创建逻辑以及编辑现有页面的逻辑。
# other imports
from wagtail.admin.forms import WagtailAdminPageForm
class BlogPageForm(WagtailAdminPageForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if not instance.pk:
# this is a NEW blog entry form - only allow title to be enabled, disable other fields
self.fields['description'].widget.attrs['readonly'] = True
if instance.pk:
# assume title has been entered and saved at this point (required for a new post)
# disable the title field
self.fields['title'].widget.attrs['readonly'] = True
def clean(self):
cleaned_data = super().clean()
instance = getattr(self, 'instance', None)
title = cleaned_data['title']
description = cleaned_data['description']
if not instance.pk:
# this is a NEW blog entry, check that only the title has been entered
if not title:
self.add_error('title', 'title must be edited before all other fields')
return cleaned_data
if description:
self.add_error('description', 'description cannot be entered until title has been completed')
if instance.pk:
# an existing blog entry, do not allow title to be changed
print('title', instance.title, title)
if instance.title != title:
self.add_error('title', 'title cannot be edited after the initial save')
class BlogPage(Page):
# ...fields
base_form_class = BlogPageForm
关于django - 有没有办法让鹡鸰体字段只读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912243/