Django admin - 如果编辑对象则删除字段 [英] Django admin - remove field if editing an object

查看:21
本文介绍了Django admin - 如果编辑对象则删除字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以通过 Django 管理区域访问的模型,如下所示:

I have a model which is accessible through the Django admin area, something like the following:

# model
class Foo(models.Model):
    field_a = models.CharField(max_length=100)
    field_b = models.CharField(max_length=100)

# admin.py
class FooAdmin(admin.ModelAdmin):
    pass

假设如果用户正在添加一个对象,我想显示 field_a 和 field_b,但如果用户正在编辑一个对象,则只显示 field_a.有没有一种简单的方法可以做到这一点,也许使用 fields 属性?

Let's say that I want to show field_a and field_b if the user is adding an object, but only field_a if the user is editing an object. Is there a simple way to do this, perhaps using the fields attribute?

如果有的话,我可以破解一个 JavaScript 解决方案,但这样做根本不对!

If if comes to it, I could hack a JavaScript solution, but it doesn't feel right to do that at all!

推荐答案

您可以为管理员创建自定义 ModelForm 以将字段拖放到 __init__

You can create a custom ModelForm for the admin to drop the field in the __init__

class FooForm(forms.ModelForm):
    class Meta(object):
        model = Foo

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            # Since the pk is set this is not a new instance
            del self.fields['field_b']

class FooAdmin(admin.ModelAdmin):
    form = FooForm

从 John 的评论中获取关于将该字段设为只读的提示,您可以将其设为隐藏字段并覆盖 clean 以确保值不会更改.

Taking a hint from John's comment about making the field read-only, you could make this a hidden field and override the clean to ensure the value doesn't change.

class FooForm(forms.ModelForm):
    class Meta(object):
        model = Foo

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            # Since the pk is set this is not a new instance
            self.fields['field_b'].widget = forms.HiddenInput()

    def clean_field_b(self):
        if self.instance and self.instance.pk:
            return self.instance.field_b
        else:
            return self.cleaned_data['field_b']  

这篇关于Django admin - 如果编辑对象则删除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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