Django在创建新对象时隐藏字段

时间:2016-10-14 18:03:16

标签: python django

我想在用户创建新对象时隐藏字段名称,但如果用户想要编辑此对象,则必须可见。 我尝试了排除方法,但是当我尝试编辑此字段时,它会使字段不可见。例如,我想隐藏状态字段。

class Toys(BaseModel):
    name = models.CharField(max_length=255)
    tags = models.ManyToManyField(Tag, related_name='Item_tags')
    price = models.CharField(max_length=255)
    status = models.BooleanField(default=False)

1 个答案:

答案 0 :(得分:1)

在您在admin.py文件中注册的模型管理员中,您可以重载get_form(self, request, obj=None, **kwargs)方法。正如您所看到的,它采用了obj参数,仅在添加时None(更改时不是None)。 从那里你可以搞乱表单以排除表单字段" name"仅在obj is None

的情况下

在Django 1.10中,该方法位于django.contrib.admin.options.ModelAdmin.get_form

编辑1 这是迄今为止不是最佳解决方案) 我无法在这里为您提供完整的解决方案,但您可以从以下内容开始:

# admin.py

from django.contrib import admin

from models import Toys


class ToysModelAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        # all the code you have in the original
        # django.contrib.admin.options.ModelAdmin.get_form
        # up to the last try except

        if obj is not None:
            defaults['fields'] = ('tags', 'price', 'status', )

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError(
                '%s. Check fields/fieldsets/exclude attributes of class %s.'
                % (e, self.__class__.__name__)
            )

admin.site.register(Toys, ToysModelAdmin)

编辑2 这是一个更好的例子

# admin.py

from collections import OrderedDict

from django.contrib import admin

from models import Toys


class ToysModelAdmin(admin.ModelAdmin):

    # this is not perfect as you'll need to keep track of your
    # model changes also here, but you won't accidentally add
    # a field that is not supposed to be editable
    _add_fields = ('tags', 'price', 'status', )

    def get_form(self, request, obj=None, **kwargs):
        model_form = super(ToysModelAdmin, self).get_form(
            request, obj, **kwargs
        )

        if obj is None:
            model_form._meta.fields = self._add_fields
            model_form.base_fields = OrderedDict(**[
                (field, model_form.base_fields[field])
                for field in self._add_fields
            ])

        return model_form