Skip to content

Instantly share code, notes, and snippets.

@aliceridgway
Last active June 25, 2022 17:19
Show Gist options
  • Save aliceridgway/591e5833a9c44711bba0264a9b86a450 to your computer and use it in GitHub Desktop.
Save aliceridgway/591e5833a9c44711bba0264a9b86a450 to your computer and use it in GitHub Desktop.
How to pass the request object to a form class. Used when form choices are specific to a particular user
class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, member):
""" Customises the labels for checkboxes"""
return "%s" % member.name
class CreateMealForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
""" Grants access to the request object so that only members of the current user
are given as options"""
self.request = kwargs.pop('request')
super(CreateMealForm, self).__init__(*args, **kwargs)
self.fields['members'].queryset = Member.objects.filter(
user=self.request.user)
class Meta:
model = Meal
fields = ['name', 'date', 'members']
name = forms.CharField()
date = forms.DateInput()
members = CustomModelMultipleChoiceField(
queryset=None,
widget=forms.CheckboxSelectMultiple
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment