如何以Django模型形式添加自定义字段? [英] How to add a custom field in django model form?

查看:328
本文介绍了如何以Django模型形式添加自定义字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表单中添加一个只读字段。

I'm trying to add a readonly field in a form.

模型文件夹已注册在其中管理网站。 FolderAdminForm 定义自定义字段统计信息文件夹模型中没有 statistcs 字段,我只想在表单上放置一些只读数据。该数据在模板中定义。

The model Folder is registered in admin site. The FolderAdminForm defines the custom field statistics. There isn't statistcs field in the Folder model, I just want to put some readonly data on the form. This data is defined in the template.

但是,只要用户没有编辑权限,我都会收到错误消息。如果用户仅具有查看权限,则会引发此错误:

But I get a error whenever the user doesn't have edit permission. If the user only have the view permission,this error is raised:

AttributeError: Unable to lookup 'statistics' on Folder or FolderAdmin

这是我的代码:

class CustomWidget(forms.Textarea):
    template_name = 'widget.html'


class FolderAdminForm(forms.ModelForm):
    class Meta:
        model = Folder
        fields = ('field1', 'field2', 'field3',)

    statistics = forms.Field(
        widget=CustomWidget,
        label='Estatísticas',
        help_text='Estatísticas da pasta',
    )


推荐答案

仅当我尝试打开没有编辑权限(即具有只读权限)的文件夹实例时,才会发生错误。因此,django将统计信息字段视为只读字段,然后搜索该字段的标签。 Django在Model,ModelAdmin中寻找此标签。由于它们都不具有统计信息属性,因此会引发错误。
因此,这对我有用:

The error only occurred whenever I tried to open a folder instance without edit permission (i.e. with read only permission). Therefore, django consider the statistics field as a read only field and then search for a label for this field. Django look for this label in Model, ModelAdmin. Since none of them has the 'statistics' attribute, the error is raised. So, this worked for me:

 class FolderAdminForm(forms.ModelForm):
    class Meta:
        model = Folder
        fields = ('field1', 'field2', 'field3',)

        labels = {'statistics': 'Estatísticas'}

    statistics = forms.Field(
        widget=CustomWidget,
        label='Estatísticas',
        help_text='Estatísticas da pasta',
    )

因此,每当django查找统计信息标签时,它都会找到该标签并且不会引发错误。我不知道为什么它不能识别作为字段参数传递的标签。

Therefore, whenever django looks for a label for statistics, it finds this label and the error is not raised. I don't know why it doesn't recognize the label passed as a Field parameter.

这篇关于如何以Django模型形式添加自定义字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆