Pass request object to the form: CBV and Form Mixins

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  1. class RequestFormKwargsMixin(object):
  2. """
  3. CBV mixin which puts the request into the form kwargs.
  4. Note: Using this mixin requires you to pop the `request` kwarg
  5. out of the dict in the super of your form's `__init__`.
  6. """
  7. def get_form_kwargs(self):
  8. kwargs = super(RequestFormKwargsMixin, self).get_form_kwargs()
  9. # Update the existing form kwargs dict with the request's user.
  10. kwargs.update({"request": self.request})
  11. return kwargs

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  1. class RequestKwargModelFormMixin(object):
  2. """
  3. Generic model form mixin for popping request out of the kwargs and
  4. attaching it to the instance.
  5. This mixin must precede forms.ModelForm/forms.Form. The form is not
  6. expecting these kwargs to be passed in, so they must be popped off before
  7. anything else is done.
  8. """
  9. def __init__(self, *args, **kwargs):
  10. self.request = kwargs.pop("request", None) # Pop the request off the passed in kwargs.
  11. 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" title="https://github.com/brack3t/django-braces">https://github.com/brack3t/django-braces.