Pass request object to the form: CBV and Form Mixins
Mar 23, 2014 · Updated: Jul 12, 2021 · by Tim Kamanin
If you want to access data from request object in your model form these two mixins will help you to do it easily:
-
You'll need a View mixin like this:
class RequestFormKwargsMixin(object): """ CBV mixin which puts the request into the form kwargs. Note: Using this mixin requires you to pop the `request` kwarg out of the dict in the super of your form's `__init__`. """ def get_form_kwargs(self): kwargs = super(RequestFormKwargsMixin, self).get_form_kwargs() # Update the existing form kwargs dict with the request's user. kwargs.update({"request": self.request}) return kwargs -
You'll need a form mixin like this:
class RequestKwargModelFormMixin(object): """ Generic model form mixin for popping request out of the kwargs and attaching it to the instance. This mixin must precede forms.ModelForm/forms.Form. The form is not expecting these kwargs to be passed in, so they must be popped off before anything else is done. """ def __init__(self, *args, **kwargs): # Pop the request off the passed in kwargs. self.request = kwargs.pop( "request", None ) super(RequestKwargModelFormMixin, self).__init__(*args, **kwargs)
Done! Enjoy this one and remember, there are lots of cool mixins in contrib apps like Django-Braces: https://github.com/brack3t/django-braces.
Hey, if you've found this useful, please share the post to help other folks find it: