De Cliss XXI
Sauter à la navigation Sauter à la recherche

Personnaliser l'interface d'admin

De quoi aller plus loin, principalement les quelques derniers slides (ce sont des choses que j'avais cherché pendant trois plombes):

Modifier le queryset dynamiquement:

class StuffAdmin(admin.ModelAdmin)
    def queryset(self, request):
        qs = super(self.__class__, self).queryset(request)
        qs = qs.filter(user=request.user)
        return qs

    # or
    def queryset(self, request):
        qs = self.model._default_manager.filter(user=request.user)
        return qs

Forcer des champs dynamiquement:

class StuffAdmin(admin.ModelAdmin)
    def save_model(self, request, object, form, change):
        object.user = request.user

Accès à la requête courante

# -*- coding: utf-8 -*-
# Passe la requête courante en variable "globale"
# Copyright (C) 2010  Cliss XXI
# This is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <>.
# Author: Sylvain Beucler

Some people apparently cannot stand thread locals, to the point they
censor and block wiki pages:
Another link:

Passing the current request is perfectly legitimate for
request-specific code such as web forms.

Passing other kind of data around might not be, but that's something
to decide on a per-case basis.

from threading import local

# Must call local() once, each call returns a different (empty) object
_cur_thread_local = local()

def get_current_request():
        return _cur_thread_local.request
        from django.core.exceptions import ImproperlyConfigured
        raise ImproperlyConfigured("Add threadlocals.ThreadLocals in your MIDDLEWARE_CLASSES setting")

class ThreadLocals(object):
    def process_request(self, request):
        _cur_thread_local.request = request
        return None  # Continue processing