Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# Imports 

2 

3from django import forms 

4from django.utils.translation import gettext_lazy as _ 

5from superdjango.contrib.i18n.languages import COMMON_LANGUAGE_CHOICES, MAX_CHOICE_LENGTH as LANGUAGE_MAX_CHOICE_LENGTH 

6from superdjango.contrib.i18n.timezones import COMMON_TIMEZONE_CHOICES, MAX_CHOICE_LENGTH as TIMEZONE_MAX_CHOICE_LENGTH 

7 

8# Exports 

9 

10__all__ = ( 

11 "FullNameChoiceField", 

12 "LanguageChoiceField", 

13 "TimeZoneChoiceField", 

14) 

15 

16# Fields 

17 

18 

19class FullNameChoiceField(forms.ModelChoiceField): 

20 """If available, uses the full name of the user for the dropdown instead of the user name. 

21 

22 **Usage** 

23 

24 In your form: 

25 

26 .. code-block:: python 

27 

28 from django.contrib.auth import get_user_model 

29 

30 user_model = get_user_model() 

31 

32 class MyModelForm(ModelForm): 

33 requested_by = FullNameChoiceField( 

34 queryset=user_model.objects.filter(is_staff=True), 

35 label=_("requested by") 

36 ) 

37 

38 """ 

39 

40 def label_from_instance(self, obj): 

41 return obj.get_full_name() or obj.username 

42 

43 

44class LanguageChoiceField(forms.ChoiceField): 

45 """A field that presents language choices. 

46 

47 By default, all ``COMMON_LANGUAGE_CHOICES`` are used. 

48 

49 """ 

50 # TODO: Determine whether LanguageChoiceField should be homed in forms.fields or in i18n. 

51 description = _("A field of language choices.") 

52 

53 def __init__(self, *args, **kwargs): 

54 kwargs.setdefault("choices", COMMON_LANGUAGE_CHOICES) 

55 kwargs['max_length'] = LANGUAGE_MAX_CHOICE_LENGTH 

56 

57 super().__init__(*args, **kwargs) 

58 

59 

60# class SlugFromField(forms.SlugField): 

61# """A slug field that provides automated slugify.""" 

62# description = _("A slug field that provides automated slugify.") 

63# 

64# def media 

65 

66class TimeZoneChoiceField(forms.ChoiceField): 

67 """A field that presents time zone choices. 

68 

69 By default, all ``COMMON_TIMEZONE_CHOICES`` are used. 

70 

71 """ 

72 # TODO: Determine whether TimeZoneChoiceField should be homed in forms.fields or in i18n. 

73 description = _("A field of time zone choices.") 

74 

75 def __init__(self, *args, **kwargs): 

76 kwargs.setdefault("choices", COMMON_TIMEZONE_CHOICES) 

77 kwargs['max_length'] = TIMEZONE_MAX_CHOICE_LENGTH 

78 

79 super().__init__(*args, **kwargs)