Skip to content

Instantly share code, notes, and snippets.

@rwoloszyn
Created June 20, 2018 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwoloszyn/f094920e49405b3131b659932ee82c3e to your computer and use it in GitHub Desktop.
Save rwoloszyn/f094920e49405b3131b659932ee82c3e to your computer and use it in GitHub Desktop.
Custom label for ModelChoicesField in django framework
class SimpleProjectModelChoicesField(ModelChoiceField):
def label_from_instance(self, obj):
return '{name}'.format(name=obj.name)
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