Skip to content

Instantly share code, notes, and snippets.

Created Jun 20, 2018
What would you like to do?
Custom label for ModelChoicesField in django framework
class SimpleProjectModelChoicesField(ModelChoiceField):
def label_from_instance(self, obj):
return '{name}'.format(
class CourseForm(ModelForm):
project = SimpleProjectModelChoicesField(queryset=Project.objects.filter(is_active=True))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
if 'project_id' in kwargs:
self.project_id = kwargs.pop("project_id")
if self.project_id is not None:
kwargs['initial'] = {'project': self.project_id}
super(CourseForm, self).__init__(*args, **kwargs)
self.fields['type'].widget.attrs.update({'class': 'form-control'})
self.fields['project'].widget.attrs.update({'class': 'form-control'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment