django admin - 添加不是模型一部分的自定义表单字段 [英] django admin - add custom form fields that are not part of the model

查看:259
本文介绍了django admin - 添加不是模型一部分的自定义表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在管理员网站上注册了一个模型。其中一个字段是长字符串表达式。我想在管理员的这个模型的添加/更新页面中添加自定义表单字段,基于这些字段值,我将构建长字符串表达式并将其保存在相关模型字段中。

I have a model registered in the admin site. One of its fields is a long string expression. I'd like to add custom form fields to the add/update page of this model in the admin that based on these fields values I will build the long string expression and save it in the relevant model field.

我该怎么做?

更新:
基本上我正在做的是从符号中构建一个数学或字符串表达式,用户选择符号(这些是不属于模型的自定义字段),当他点击保存时,我从符号列表中创建一个字符串表达式表达式并将其存储在数据库中。我不希望这些符号是模型和数据库的一部分,只是最后的表达式。

UPDATE: Basically what I'm doing is building a mathematical or string expression from symbols, the user chooses symbols (these are the custom fields that are not part of the model) and when he clicks save then I create a string expression representation from the list of symbols and store it in the DB. I don't want the symbols are part of the model and DB, only the final expression.

推荐答案

py或在一个单独的forms.py中,您可以添加一个ModelForm类,然后按照通常的方式声明其中的额外字段。我还给了一个例子,说明如何在form.save()中使用这些值:

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

要在admin中显示额外的字段:

To have the extra fields appearing in the admin just:


  1. 编辑您的admin.py并设置表单属性以引用您上面创建的表单

  2. 包括您的新您的字段或字段中的字段声明

像这样:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

更新:
在django 1.8中,您需要将 fields ='__all __'添加到YourModelForm的元类。

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.

这篇关于django admin - 添加不是模型一部分的自定义表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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