5

I would like admin to be able to edit a field that normal users would be unable to edit. Examples would be author or subscribers etc.

I tried this: Django admin: How to display a field that is marked as editable=False' in the model?

(the editable part given in an answer)

But the field still fails to appear on the admin page.

For reference here's some info:

#models.py
class MyModel(models.Model):
    myfield = models.ManyToManyField(User, blank=True, editable=False)

#admin.py
class MyModelAdminForm(forms.ModelForm):
    myfield = models.ManyToManyField(User, blank=True, editable=True)

    class Meta(object):
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm

admin.site.register(MyModel, MyModelAdmin)

If I change the model to state editable=True then I see the field on my admin page. (as expected)

I'm using Django 1.3, Python 2.6

Community
  • 1
  • 1
powlo
  • 2,538
  • 3
  • 28
  • 38
  • 2
    This type of field needed not for this puposes. It needed for saving system created data like `my_field = models.DateTimeField(auto_now_add=True, editable=False)`. You can create rules for `MyModelAdmin` where check is user superadmin or just user and show it another fields list. – b1_ Jul 19 '12 at 11:54
  • 1
    maybe this can help you [Hide certain fields in Django admin site for different user](http://stackoverflow.com/a/10356566/430408) – urcm Jul 19 '12 at 12:42
  • 1
    @b1- Thinking about it you're right. editable=False fields should only be used on fields that are set outside the form. Since I'm insisting that the field is displayed in the form then this is the wrong parameter. An [exclude list](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude) is a better option. – powlo Jul 19 '12 at 13:40
  • 1
    @b1 What about editing these fields in automated tests (aka unit tests)? – Buttons840 Sep 27 '13 at 23:27
  • @Buttons840 What for? Better check in tests: Is model automatically save in field correct value or not? – b1_ Sep 28 '13 at 08:32

1 Answers1

0

You should be handling this use case via permissions: only user that have the change permission for a Model are allowed to really change it. These permissions exist by default in Django. You simply need to check them before displaying the form.

They can also be used for finer grained control like only showing certain fields. But that logic has to be implemented by you in your views and templates.

Have a look at: https://docs.djangoproject.com/en/1.11/topics/auth/default/#default-permissions

If you still need to edit non-editable field, have a look at: https://stackoverflow.com/a/44720169/621690

Risadinha
  • 16,058
  • 2
  • 88
  • 91