Add custom ModelForm class that supports field choice sorting. Use the new form class to sort the user profile language field and the document language fields. Thanks to Baptiste GAILLET @bat79a for the original idea. GitLab issue #292.

This commit is contained in:
Roberto Rosario
2016-05-19 18:14:29 -04:00
parent 004b8c9054
commit 4de3bb99e2
3 changed files with 45 additions and 4 deletions

View File

@@ -1,5 +1,6 @@
from __future__ import unicode_literals
from operator import itemgetter
import os
from django import forms
@@ -114,10 +115,44 @@ class LicenseForm(FileDisplayForm):
FILENAME = 'LICENSE'
class LocaleProfileForm(forms.ModelForm):
class ModelForm(forms.ModelForm):
"""
ModelForm subclass that supports field choices sorting
class Meta:
# Dictionary of field names and the key used to sort the field
sorted_fields = None
# Example:
# sorted_fields = {'language': operator.itemgetter(1))}
"""
def __init__(self, *args, **kwargs):
super(ModelForm, self).__init__(*args, **kwargs)
for field, key in getattr(self.Meta, 'sorted_fields', {}).items():
# Would be the cleaner "opts.sorted_fields" if these were addressed
# https://code.djangoproject.com/ticket/5793
# of a get_options_class for Forms/ModelForms
# https://code.djangoproject.com/ticket/18540
choices = self.fields[field].choices
if not self.fields[field].required:
# Remove empty choice before sorting
empty_choice = choices.pop(0)
self.fields[field].choices = sorted(choices, key=key)
if not self.fields[field].required:
# Add empty choice after sorting
self.fields[field].choices.insert(0, empty_choice)
class LocaleProfileForm(ModelForm):
class Meta:
fields = ('language', 'timezone')
model = UserLocaleProfile
sorted_fields = {'language': itemgetter(1)}
class LocaleProfileForm_view(DetailForm):