django admin在修改obj时使字段为只读,但在添加新obj时需要

时间:2010-12-03 08:02:51

标签: django django-admin

在admin中我想在修改对象时禁用一个字段,但在添加新对象时需要它。

django怎么回事这个?

8 个答案:

答案 0 :(得分:144)

您可以覆盖管理员的get_readonly_fields方法:

class MyModelAdmin(admin.ModelAdmin):

    def get_readonly_fields(self, request, obj=None):
        if obj: # editing an existing object
            return self.readonly_fields + ('field1', 'field2')
        return self.readonly_fields

答案 1 :(得分:10)

如果您想在更改视图上将所有字段设置为只读,请覆盖管理员的get_readonly_fields:

def get_readonly_fields(self, request, obj=None):
    if obj: # editing an existing object
        # All model fields as read_only
        return self.readonly_fields + tuple([item.name for item in obj._meta.fields])
    return self.readonly_fields

如果您想在更改视图中隐藏保存按钮

  1. 更改视图

    def change_view(self, request, object_id, form_url='', extra_context=None):
        ''' customize edit form '''
        extra_context = extra_context or {}
        extra_context['show_save_and_continue'] = False
        extra_context['show_save'] = False
        extra_context['show_save_and_add_another'] = False # this not works if has_add_permision is True
        return super(TransferAdmin, self).change_view(request, object_id, extra_context=extra_context)
    
  2. 如果用户尝试编辑,则更改权限:

    def has_add_permission(self, request, obj=None):
       # Not too much elegant but works to hide show_save_and_add_another button
        if '/change/' in str(request):
            return False
        return True
    

    此解决方案已在 Django 1.11

  3. 上进行了测试

答案 2 :(得分:3)

仅供参考:如果其他人遇到我遇到的同样两个问题:

  1. 您仍然应该在类的主体中声明任何永久readonly_fields,因为将从验证访问readonly_fields类属性(请参阅django.contrib.admin.validation:validate_base(),line.213 appx)< / p>

  2. 这不适用于Inlines,因为传递给get_readonly_fields()的obj是父obj(我有两个使用css或js的hacky和低安全性解决方案)

答案 3 :(得分:2)

基于Bernhard Vallant之前的优秀建议的变体,它也保留了基类提供的任何可能的定制(如果有的话):

class MyModelAdmin(BaseModelAdmin):

    def get_readonly_fields(self, request, obj=None):
        readonly_fields = super(MyModelAdmin, self).get_readonly_fields(request, obj)
        if obj: # editing an existing object
            return readonly_fields + ['field1', ..]
        return readonly_fields

答案 4 :(得分:0)

您可以通过覆盖ModelAdmin的formfield_for_foreignkey方法来完成此操作:

from django import forms
from django.contrib import admin

from yourproject.yourapp.models import YourModel

class YourModelAdmin(admin.ModelAdmin):

    class Meta:
        model = YourModel

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        # Name of your field here
        if db_field.name == 'add_only':
            if request:
                add_opts = (self._meta.app_label, self._meta.module_name)
                add = u'/admin/%s/%s/add/' % add_opts
                if request.META['PATH_INFO'] == add:
                    field = db_field.formfield(**kwargs)
                else:
                    kwargs['widget'] = forms.HiddenInput()
                    field = db_field.formfield(**kwargs)
            return field
        return admin.ModelAdmin(self, db_field, request, **kwargs)

答案 5 :(得分:0)

遇到了类似的问题。我在ModelAdmin中用“add_fieldsets”和“restricted_fieldsets”解决了这个问题。

from django.contrib import admin  
class MyAdmin(admin.ModelAdmin):
 declared_fieldsets = None
 restricted_fieldsets = (
    (None, {'fields': ('mod_obj1', 'mod_obj2')}),
    ( 'Text', {'fields': ('mod_obj3', 'mod_obj4',)}),
 )

 add_fieldsets = (
            (None, {
             'classes': ('wide',),
             'fields': ('add_obj1', 'add_obj2', )}),
             )

请参阅例如:http://code.djangoproject.com/svn/django/trunk/django/contrib/auth/admin.py

但这并不能保护您的模型免受以后“add_objX”更改的影响。 如果你也想要这个,我认为你必须在模型类“保存”功能上检查并检查那里的变化。

请参阅:www.djangoproject.com/documentation/models/save_delete_hooks /

Greez,尼克

答案 6 :(得分:0)

对于Django 2.2.x来说,内联表单的情况仍未得到解决,但是solution from John实际上非常聪明。

代码略微适合我的情况:

class NoteListInline(admin.TabularInline):
""" Notes list, readonly """
    model = Note
    verbose_name = _('Note')
    verbose_name_plural = _('Notes')
    extra = 0
    fields = ('note', 'created_at')
    readonly_fields = ('note', 'created_at')

    def has_add_permission(self, request, obj=None):
    """ Only add notes through AddInline """
    return False

class NoteAddInline(admin.StackedInline):
    """ Notes edit field """
    model = Note
    verbose_name = _('Note')
    verbose_name_plural = _('Notes')
    extra = 1
    fields = ('note',)
    can_delete = False

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        return queryset.none()  # no existing records will appear

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    # ...
    inlines = (NoteListInline, NoteAddInline)
    # ...

答案 7 :(得分:0)

对Bernhard和Mario出色解决方案的更可插入的解决方案,将对createonly_fields模拟的支持添加到readonly_fields:

class MyModelAdmin(admin.ModelAdmin):

    # ModelAdmin configuration as usual goes here

    createonly_fields = ['title', ]

    def get_readonly_fields(self, request, obj=None):
        readonly_fields = list(super(MyModelAdmin, self).get_readonly_fields(request, obj))
        createonly_fields = list(getattr(self, 'createonly_fields', []))
            
        if obj:  # editing an existing object
            readonly_fields.extend(createonly_fields)
        return readonly_fields