Pass request object to the form: CBV and Form Mixins

23 Mar · by Tim Kamanin · 1 min read

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:

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:

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:

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials