Created
June 20, 2018 22:48
-
-
Save rwoloszyn/f094920e49405b3131b659932ee82c3e to your computer and use it in GitHub Desktop.
Custom label for ModelChoicesField in django framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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