django Initialising Choices in Form from Class Based View

The view:

from django.views.generic import FormView

class EmailView(FormView):
    # ...

    def get_form_kwargs(self):
        kwargs = super(EmailView, self).get_form_kwargs()

        # get users, note: you can access request using: self.request

        kwargs['users'] = users
        return kwargs

The form:

from django import forms import Form

class EmailForm(Form):

    users = MultipleChoiceField(required=False)
    # ...

    def __init__(self, *args, **kwargs):
        self.users = kwargs.pop('users', None)
        super(EmailForm, self).__init__(*args, **kwargs) 
        self.fields['users'].choices = self.users

Basically, what I've done in a similar case is the following (Python 3.5, Django 1.8):

def get_form(self, *args, **kwargs):
    form= super().get_form(*args, **kwargs)
    form.fields['rank'].choices= <sequence of 2-tuples>
    return form

where obviously rank is the field name. This way I use the default form.


Alright, the FormMixin calls get_form to get the form-class which looks like

def get_form(self, form_class):
    """
    Returns an instance of the form to be used in this view.
    """
    return form_class(**self.get_form_kwargs())

So you can either override get_form to instance your Form yourself

def get_form(self, form_class):
    return EmailForm(files=self.request.FILES or None,
                     data=self.request.POST or None,
                     users=some_user_queryset)

or stay a bit more generic and override get_form_kwargs to something like

def get_form_kwargs(self):
    form_kws = super(EmailView, self).get_form_kwargs()
    form_kws["users"] = some_user_queryset
    return form_kws