Django admin - how to hide some fields in User edit?

7,085 views
Skip to first unread message

galgal

unread,
Jul 4, 2011, 4:59:04 PM7/4/11
to django...@googlegroups.com
How can I hide fields in admin User edit? Mainly I want to hide permissions and groups selecting in some exceptions, but exclude variable doesn't work :/

leo

unread,
Jul 4, 2011, 5:16:04 PM7/4/11
to django...@googlegroups.com, galgal
try to modify this file "Python26\Lib\site-packages\django\contrib\auth\admin.py"

find this line
        (_('Groups'), {'fields': ('groups',)}),

comment this line you will remove groups


On 2011-7-5 4:59, galgal wrote:
How can I hide fields in admin User edit? Mainly I want to hide permissions and groups selecting in some exceptions, but exclude variable doesn't work :/
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/ydsmKWUyXQMJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

--
chlin

galgal

unread,
Jul 4, 2011, 5:19:41 PM7/4/11
to django...@googlegroups.com, galgal
I'm rather searchung the way to do that in my admin.py file not in core files.

Michał Sawicz

unread,
Jul 4, 2011, 6:09:09 PM7/4/11
to django...@googlegroups.com, galgal
Dnia 2011-07-04, pon o godzinie 14:19 -0700, galgal pisze:

> I'm rather searchung the way to do that in my admin.py file not in
> core files.

Obviously the proposal was... fundamentally wrong.

Create your own UserAdmin, unregister the one registered by
django.contrib.admin and register your own.

> admin.site.unregister(User)
> admin.site.register(User, MyUserAdmin)
--
Michał (Saviq) Sawicz <mic...@sawicz.net>

signature.asc

galgal

unread,
Jul 4, 2011, 6:13:06 PM7/4/11
to django...@googlegroups.com, galgal
That's my code now - how to hide groups for example?

admin.site.unregister(User)
class UserProfileInline(admin.StackedInline):
    model = UserProfile
    filter_horizontal = ('cities',)
    extra = 1
    max_num = 1
    filter_horizontal = ('cities',)

class UserProfileAdmin(UserAdmin):
    inlines = [UserProfileInline,]
    list_filter = ('userprofile__type','userprofile__cities',)
    search_fields = ['userprofile__type', 'username', 'userprofile__cities__name', 'email', 'first_name', 'last_name',]

    # show users list - if user_id=1 show all, else: show id's > 1
    def queryset(self, request):
        qs = super(UserProfileAdmin, self).queryset(request)
        if request.user.id == 1:
            return qs
        return qs.filter(id__gt=1)

admin.site.register(User, UserProfileAdmin)

Michał Sawicz

unread,
Jul 4, 2011, 6:17:18 PM7/4/11
to django...@googlegroups.com, galgal
Dnia 2011-07-04, pon o godzinie 15:13 -0700, galgal pisze:

> That's my code now - how to hide groups for example?

Have you tried reading the Django Admin docs? [1] [2]

[1] https://docs.djangoproject.com/en/1.3/ref/contrib/admin/
[2]
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.exclude

P.S. please fix your e-mail client not to translate "Re:" in responses'
subjects.

signature.asc

galgal

unread,
Jul 4, 2011, 6:20:06 PM7/4/11
to django...@googlegroups.com, galgal
Yes I read it.  exclude = ('groups',) throws:
Caught KeyError while rendering: "Key 'groups' not found in Form"

Michał Sawicz

unread,
Jul 4, 2011, 6:44:02 PM7/4/11
to django...@googlegroups.com, galgal
Dnia 2011-07-04, pon o godzinie 15:20 -0700, galgal pisze:

> Yes I read it. exclude = ('groups',) throws:
> Caught KeyError while rendering: "Key 'groups' not found in Form"

That's because the stock UserAdmin defines fieldsets in which 'groups'
is a field, you need to modify the fieldsets, too. [1]

[1]
https://code.djangoproject.com/browser/django/trunk/django/contrib/auth/admin.py#L27

signature.asc

galgal

unread,
Jul 5, 2011, 6:13:33 PM7/5/11
to django...@googlegroups.com, galgal
I made it in that way, and it works:
def get_fieldsets(self, request, obj=None):
        if obj:
            if request.user.id == 1:
                return self.declared_fieldsets
            else:
                if obj.get_profile().type==1:
                    return (
                        (None, {'fields': ('username', 'password')}),
                        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
                        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
                    )
                else:
                    return (
                        (None, {'fields': ('username', 'password')}),
                        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
                        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'user_permissions')}),
                        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
                    )
        else:
            return self.add_fieldsets

Michał Sawicz

unread,
Jul 5, 2011, 7:49:17 PM7/5/11
to django...@googlegroups.com, galgal
Dnia 2011-07-05, wto o godzinie 15:13 -0700, galgal pisze:

> I made it in that way, and it works:
Remember that you need to exclude the field from the form, too, if you
don't want malicious attempts to inject the groups to work.
signature.asc

galgal

unread,
Jul 6, 2011, 3:31:18 AM7/6/11
to django...@googlegroups.com, galgal
Ok but like I said in previous post, exclude = ('groups',) etc doesn't work :/

Michał Sawicz

unread,
Jul 6, 2011, 3:36:43 AM7/6/11
to django...@googlegroups.com, galgal
Dnia 2011-07-06, śro o godzinie 00:31 -0700, galgal pisze:

> Ok but like I said in previous post, exclude = ('groups',) etc doesn't
> work :/

It does, you just need to override both exclude / fields _and_
fieldsets.

The exception you've mentioned resulted from the fact that you've
excluded the field from the form, but the fieldsets still defined it as
one of the elements, so the form failed.

signature.asc

galgal

unread,
Jul 6, 2011, 4:16:19 PM7/6/11
to django...@googlegroups.com, galgal
Any idea how to overwrite it dynamically?
def get_form(self, request, obj=None, **kwargs):
        self.exclude = ('user_permissions',)
        return super(UserProfileAdmin, self).get_form(request, obj=None, **kwargs)
Throws:

TemplateSyntaxError at /admin/auth/user/2/

Caught KeyError while rendering: "Key 'password' not found in Form"

galgal

unread,
Jul 6, 2011, 5:40:21 PM7/6/11
to django...@googlegroups.com, galgal
Full code:
class UserProfileAdmin(UserAdmin):
    inlines = [UserProfileInline,]
    list_filter = ('userprofile__type','userprofile__cities',)
    search_fields = ['userprofile__type', 'username', 'userprofile__cities__name', 'email', 'first_name', 'last_name',]

    # show users list - if user_id=1 show all, else: show id's > 1
    def queryset(self, request):
        qs = super(UserProfileAdmin, self).queryset(request)
        if request.user.id == 1:
            return qs
        return qs.filter(id__gt=1)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "user_permissions":
            if not request.user.is_superuser:
                #from django.contrib.auth.models import Permission
                #kwargs["queryset"] = Permission.objects.filter(content_type=12)
                kwargs["queryset"] = request.user.user_permissions
        return super(UserProfileAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
    def get_form(self, request, obj=None, **kwargs):
        if obj:
            if obj.get_profile().type==1:
                self.exclude = ('user_permissions',)
        return super(UserProfileAdmin, self).get_form(request, obj=None, **kwargs)

Stacktrace:

TemplateSyntaxError at /admin/auth/user/2/

Caught KeyError while rendering: "Key 'password' not found in Form"
Request Method:GET
Request URL:http://localhost:8000/admin/auth/user/2/
Django Version:1.3
Exception Type:TemplateSyntaxError
Exception Value:
Caught KeyError while rendering: "Key 'password' not found in Form"
Exception Location:C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\forms\forms.py in __getitem__, line 106
Python Executable:C:\Python27\python.exe
Python Version:2.7.1

Template error

In template c:\python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 6

Caught KeyError while rendering: "Key 'password' not found in Form"

1<fieldset class="module aligned {{ fieldset.classes }}">
2 {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
3 {% if fieldset.description %}
4 <div class="description">{{ fieldset.description|safe }}</div>
5 {% endif %}
6 {% for line in fieldset %}
7 <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %} {{ field.field.name }}{% endfor %}">
8 {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
9 {% for field in line %}
10 <div{% if not line.fields|length_is:'1' %} class="field-box{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}>
11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
12 {% if field.is_checkbox %}
13 {{ field.field }}{{ field.label_tag }}
14 {% else %}
15 {{ field.label_tag }}
16 {% if field.is_readonly %} and the longest part:
Environment:

Request Method: GETRequest URL: http://localhost:8000/admin/auth/user/2/
Django Version: 1.3Python Version: 2.7.1Installed Applications:['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'debug_toolbar', 'templatelibrary', 'apps.index', 'apps.city']Installed Middleware:('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware')

Template error:In template c:\python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 6
   Caught KeyError while rendering: "Key 'password' not found in Form"
   1 : <fieldset class="module aligned {{ fieldset.classes }}">

   2 :     {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}

   3 :     {% if fieldset.description %}

   4 :         <div class="description">{{ fieldset.description|safe }}</div>

   5 :     {% endif %}

   6 :      {% for line in fieldset %} 

   7 :         <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %} {{ field.field.name }}{% endfor %}">

   8 :             {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}

   9 :             {% for field in line %}

   10 :                 <div{% if not line.fields|length_is:'1' %} class="field-box{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}>

   11 :                     {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}

   12 :                     {% if field.is_checkbox %}

   13 :                         {{ field.field }}{{ field.label_tag }}

   14 :                     {% else %}

   15 :                         {{ field.label_tag }}

   16 :                         {% if field.is_readonly %}

Traceback:File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\handlers\base.py" in get_response  111.                         response = callback(request, *callback_args, **callback_kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\options.py" in wrapper  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\utils\decorators.py" in _wrapped_view  93.                     response = view_func(request, *args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\views\decorators\cache.py" in _wrapped_view_func  79.         response = view_func(request, *args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\sites.py" in inner  197.             return view(request, *args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\utils\decorators.py" in _wrapper  28.             return bound_func(*args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\utils\decorators.py" in _wrapped_view  93.                     response = view_func(request, *args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\utils\decorators.py" in bound_func  24.                 return func(self, *args2, **kwargs2)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\transaction.py" in inner  217.                 res = func(*args, **kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\options.py" in change_view  1030.         return self.render_change_form(request, context, change=True, obj=obj)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\options.py" in render_change_form  708.         ], context, context_instance=context_instance)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\shortcuts\__init__.py" in render_to_response  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\loader.py" in render_to_string  188.         return t.render(context_instance)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  123.             return self._render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in _render  117.         return self.nodelist.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  744.                 bits.append(self.render_node(node, context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\debug.py" in render_node  73.             result = node.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\loader_tags.py" in render  127.         return compiled_parent._render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in _render  117.         return self.nodelist.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  744.                 bits.append(self.render_node(node, context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\debug.py" in render_node  73.             result = node.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\loader_tags.py" in render  127.         return compiled_parent._render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in _render  117.         return self.nodelist.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  744.                 bits.append(self.render_node(node, context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\debug.py" in render_node  73.             result = node.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\loader_tags.py" in render  64.             result = block.nodelist.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  744.                 bits.append(self.render_node(node, context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\debug.py" in render_node  73.             result = node.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\defaulttags.py" in render  227.                 nodelist.append(node.render(context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\loader_tags.py" in render  159.         return self.render_template(self.template, context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\loader_tags.py" in render_template  141.         output = template.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  123.             return self._render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in _render  117.         return self.nodelist.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\base.py" in render  744.                 bits.append(self.render_node(node, context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\debug.py" in render_node  73.             result = node.render(context)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\defaulttags.py" in render  227.                 nodelist.append(node.render(context))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\template\defaulttags.py" in render  190.             values = list(values)File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\helpers.py" in __iter__  105.                 yield AdminField(self.form, field, is_first=(i == 0))File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\contrib\admin\helpers.py" in __init__  112.         self.field = form[field] # A django.forms.BoundField instanceFile "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\forms\forms.py" in __getitem__  106.             raise KeyError('Key %r not found in Form' % name)
Exception Type: TemplateSyntaxError at /admin/auth/user/2/Exception Value: Caught KeyError while rendering: "Key 'password' not found in Form"

galgal

unread,
Jul 6, 2011, 5:41:11 PM7/6/11
to django...@googlegroups.com, galgal

Michał Sawicz

unread,
Jul 6, 2011, 5:56:05 PM7/6/11
to django...@googlegroups.com, galgal
Dnia 2011-07-06, śro o godzinie 14:40 -0700, galgal pisze:

> Full code:
> class UserProfileAdmin(UserAdmin):
> inlines = [UserProfileInline,]
> list_filter = ('userprofile__type','userprofile__cities',)
> search_fields = ['userprofile__type', 'username',
> 'userprofile__cities__name', 'email', 'first_name', 'last_name',]

Use tuples instead of lists, they're cheaper. And lists don't require
the trailing comma.

--8<--

Why not using super().get_fieldsets() when there is no object or your
user isn't 1?

> def get_form(self, request, obj=None, **kwargs):
> if obj:
> if obj.get_profile().type==1:
> self.exclude = ('user_permissions',)
> return super(UserProfileAdmin, self).get_form(request,
> obj=None, **kwargs)

Should be obj=obj, not obj=None, you're always getting a new user form.

signature.asc

Michał Sawicz

unread,
Jul 6, 2011, 5:29:39 PM7/6/11
to django...@googlegroups.com, galgal
Dnia 2011-07-06, śro o godzinie 13:16 -0700, galgal pisze:

That exception is irrelevant to the code you provided. Paste full code
and full backtrace.

signature.asc
Reply all
Reply to author
Forward
0 new messages