DjangoDjango

Pass request object to the form: CBV and Form Mixins

Mar 23, 2014 · Updated: Nov 10, 2017 · 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:

1) You'll need a View mixin like this:

python
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

2) You'll need a form mixin like this:

python
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):
  self.request = kwargs.pop("request", None)  # Pop the request off the passed in kwargs.
  super(RequestKwargModelFormMixin, self).__init__(*args, **kwargs)

3) Simple! 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:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓