在 Django admin 中禁用选择列表,仅用于编辑 [英] Disable choice list in Django admin, only for editing

查看:32
本文介绍了在 Django admin 中禁用选择列表,仅用于编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在编辑对象时禁用某些字段.我已设法为文本字段执行此操作,但对于下拉列表(选择列表)而言,这是不可能的.

I want to disable some fields when I am editing an object. I have managed to do this for text fields, but it's been impossible for a dropdown list (choice list).

我正在表单的构造函数中执行此操作.

I am doing this action in the constructor of the form.

class OrderModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['description'].widget.attrs['readonly'] = True
            self.fields['city_code'].widget.attrs['disabled'] = True

请注意我是如何使用不同的关键字为两者制作的,但我无法为我的 customer_id 字段制作.

Notice how I made it for both with different keywords, but I can't do it for my customer_id field.

推荐答案

将属性设置为 disabledreadonly 只会影响小部件的显示方式.它实际上并没有阻止某人提交更改这些字段的帖子请求.

Setting the attribute to disabled or readonly only affects the way the widgets are displayed. It doesn't actually stop somebody submitting a post request that changes those fields.

这可能是一个更好的方法来覆盖 get_readonly_fields 适用于您的模型.

It might be a better approach to override get_readonly_fields for your model.

class OrderModelAdmin(admin.Model
    def get_readonly_fields(self, request, obj=None):
        if self.obj.pk:
            return ['description', 'city_code', 'customer']
        else:
            return []

这篇关于在 Django admin 中禁用选择列表,仅用于编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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