0

I would like to be able to access request object in django admins clean() method. How can I customize this getting the user from a admin validation class to work with django admins modelform

What kind of modification do i need to make to change_view below

def change_view(self, request, object_id, extra_context=None):
    self.form = GroupForm
    result = super(GroupsAdmin, self).change_view(request, object_id, extra_context)

    return result

so that it calls the constructor below which has the request argument

class GroupForm(forms.ModelForm):
    class Meta:
        model = Group

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(GroupForm, self).__init__(*args, **kwargs)
Community
  • 1
  • 1
domino
  • 2,137
  • 1
  • 22
  • 30

1 Answers1

1

Seeing as no answer was ever provided for this, I figured I should highlight how I resolved this just in case someone else might find the info useful.

I eventually solved this on defining a custom middleware and using ThreadLocals.

First define a ThreadLocals class in your forms.py as shown below

import threading
_thread_locals = threading.local()

class ThreadLocals(object):
    """
    Middleware that gets various objects from the
    request object and saves them in thread local storage.
    """
    def process_request(self, request):
        _thread_locals.request = request

Then in your settings.py make sure to enable the middleware

MIDDLEWARE_CLASSES = (
    'myproject.myapp.forms.ThreadLocals',
)

And finally accessing the request object is as easy as

class GroupForm(forms.ModelForm):
    class Meta:
        model = Group

        def clean(self):
            cleaned_data = super(GroupForm, self).clean()
            self.request = _thread_locals.request
domino
  • 2,137
  • 1
  • 22
  • 30