Django admin:隐藏新记录上的只读字段?

发布于 2024-10-19 00:08:06 字数 619 浏览 1 评论 0原文

我正在使用 Django 管理站点,其中记录上有一些只读字段:

class BookAdmin(admin.ModelAdmin):
    fieldsets = [
    (None, {'fields': ['title', 'library_id', 'is_missing', \
                       'transactions_all_time']}),
    ]
    readonly_fields = ['transactions_all_time',]
    list_display = ('library_id', 'author', 'title')

这在编辑记录时非常有用 - transactions_all_time 字段是只读的,正如我想要的那样。

然而,当添加新记录时,它的行为有点奇怪。我在页面底部看到一个只读部分,我无法编辑该部分,并且此时该部分无关紧要。

如果在添加新记录时根本不存在该字段会好得多。

是否有任何 Django 选项可以在添加新记录时不显示只读字段?我知道我可以破解 add_form.html 上的 CSS 来隐藏它,但是有更好的方法吗?

谢谢。

I'm using the Django admin site with some readonly fields on records:

class BookAdmin(admin.ModelAdmin):
    fieldsets = [
    (None, {'fields': ['title', 'library_id', 'is_missing', \
                       'transactions_all_time']}),
    ]
    readonly_fields = ['transactions_all_time',]
    list_display = ('library_id', 'author', 'title')

This works great when editing records - the transactions_all_time field is read-only, just as I want.

However, when adding new records it behaves a bit oddly. I get a read-only section at the bottom of the page, which I can't edit and which is irrelevant at this point.

It would be much better if this field was not present at all when adding new records.

Is there any Django option for not displaying read-only fields while adding a new record? I know I can hack the CSS on add_form.html to hide it, but is there a better way?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半仙 2024-10-26 00:08:06

我有类似的问题。像这样解决了

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ('field_one',)
    def get_readonly_fields(self, request, obj=None):
        if obj: # Editing
            return self.readonly_fields
        return ()

I had similar problem. Resolved it like this

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ('field_one',)
    def get_readonly_fields(self, request, obj=None):
        if obj: # Editing
            return self.readonly_fields
        return ()
若沐 2024-10-26 00:08:06

这是 Kushal 解决方案的 DRY 版本:

def get_fieldsets(self, request, obj=None):
    def if_editing(*args):
        return args if obj else ()
    return (
        (None, {
            'classes': ('wide',),
            'fields': if_editing('admin_thumb', 'admin_image',) +
                      ('original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )  

请注意,这仅适用于主窗体 - 在内联窗体上,您传递的是主 obj,而不是内联 obj。

Here's a DRY version of Kushal's solution:

def get_fieldsets(self, request, obj=None):
    def if_editing(*args):
        return args if obj else ()
    return (
        (None, {
            'classes': ('wide',),
            'fields': if_editing('admin_thumb', 'admin_image',) +
                      ('original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )  

Note that this only works on the main form -- on an inline form, you're passed the main obj, not the inline obj.

抱猫软卧 2024-10-26 00:08:06

我遇到了类似的问题,但解决方案略有不同。我想从“新”表单(“添加”视图)隐藏图像预览(只读字段),但在获取新对象时显示它们:

class PhotoAdmin(admin.ModelAdmin):
readonly_fields = ('admin_image', 'admin_thumb', )
search_fields = ('filename', 'user', 'supplier', 'customer')
list_display= ('admin_thumb','filename', 'user', 'supplier', 'customer')
#fields = ('admin_thumb', 'admin_image', 'original_image', 'user', 'supplier', 'customer')


def get_fieldsets(self, request, obj=None):
    fieldset_existing = (
        (None, {
            'classes': ('wide',),
            'fields': ('admin_thumb', 'admin_image',
                'original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )
    fieldset_new = (
        (None, {
            'classes': ('wide',),
            'fields': ('original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )
    if obj: # Editing
        return fieldset_existing
    return fieldset_new

#fields 行显示原始字段。我承认这个解决方案不是很“干”,但它很清晰且简单。

I had a similar problem with a slightly different solution. I wanted to hide image previews (read only fields) from the 'new' form (the 'add' view) but display them when fetching a new object:

class PhotoAdmin(admin.ModelAdmin):
readonly_fields = ('admin_image', 'admin_thumb', )
search_fields = ('filename', 'user', 'supplier', 'customer')
list_display= ('admin_thumb','filename', 'user', 'supplier', 'customer')
#fields = ('admin_thumb', 'admin_image', 'original_image', 'user', 'supplier', 'customer')


def get_fieldsets(self, request, obj=None):
    fieldset_existing = (
        (None, {
            'classes': ('wide',),
            'fields': ('admin_thumb', 'admin_image',
                'original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )
    fieldset_new = (
        (None, {
            'classes': ('wide',),
            'fields': ('original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )
    if obj: # Editing
        return fieldset_existing
    return fieldset_new

The #fields line shows the original fields. I admit this solution is not very 'DRY' but it's clear and simple.

别念他 2024-10-26 00:08:06

另一种选择是在原始模型中设置 editable 参数。

class Book(models.Model):
    transactions_all_time = models.BooleanField(editable=False)

您的 ModelAdmin 将不会在版本中显示该字段,该字段将被排除。

another alternative is that you set the editable arg in the original Model.

class Book(models.Model):
    transactions_all_time = models.BooleanField(editable=False)

your ModelAdmin will not show the field in edition, the field will get excluded.

静水深流 2024-10-26 00:08:06

这就是我最终从“添加”页面隐藏 readonly_fields 的方式:

class MyAdmin(admin.ModelAdmin):

    readonly_fields = ['foo', 'bar']

    def get_exclude(self, request, obj=None):
        exclude = super().get_exclude(request, obj)
        if obj is None:
            # Adding a new one
            exclude = (exclude or []) + self.readonly_fields
        return exclude

如果没有这个,创建新对象时会显示“foo”和“bar”,并且 - 尽管是只读的 - 页面也会显示由各自的字段默认函数生成的值不是保存的实际值,这令人困惑。

例如,foo = models.DateTimeField(default=django.utils.timezone.now) 显示了加载“Add”页面的时间,但生成的创建对象具有表单的时间已提交。或者,带有 default=uuid.uuid4 的字段显示“添加”页面上显示的完全随机值,然后在保存时将其丢弃并替换为另一个值。

readonly_fields 说:

它们也被排除在用于创建和编辑的 ModelForm 之外

,但情况似乎并非如此,尽管 Django 代码 似乎表明它们是 - 所以如果有人可以解释为什么我需要添加上面的 get_exclude 覆盖以获得此行为我有兴趣听到!也许“从模型表单中排除”并不一定意味着它们不在页面上?

This is how I ended up hiding the readonly_fields from the 'Add' page:

class MyAdmin(admin.ModelAdmin):

    readonly_fields = ['foo', 'bar']

    def get_exclude(self, request, obj=None):
        exclude = super().get_exclude(request, obj)
        if obj is None:
            # Adding a new one
            exclude = (exclude or []) + self.readonly_fields
        return exclude

Without this 'foo' and 'bar' were shown when creating a new object and - despite being read-only - the page showed values generated by their respective field default functions but not the actual values that get saved which is confusing.

For example foo = models.DateTimeField(default=django.utils.timezone.now) was showing up with the time the 'Add' page was loaded, but the resultant created object had the time the form was submitted. Or a field with default=uuid.uuid4 shows a completely random value shown on the 'Add' page, which is then thrown away and replaced with another on save.

The documentation for readonly_fields says:

they are also excluded from the ModelForm used for creating and editing

yet this does not appear to be the case, despite the Django code appearing to suggest that they are - so if anyone can explain why I need to add the above get_exclude override to get this behaviour I would be interested to hear! Maybe 'excluded from the ModelForm' doesn't necessarily mean they aren't on the page?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文