|
| 1 | +from django import forms |
| 2 | +from .validators import * |
| 3 | +from .params import * |
| 4 | + |
| 5 | + |
| 6 | +class ForeignKeyField(forms.ModelChoiceField): |
| 7 | + pass |
| 8 | + |
| 9 | +class ForeignKeyChoiceField(forms.ChoiceField): |
| 10 | + pass |
| 11 | + |
| 12 | +class GeneratorField(forms.CharField): |
| 13 | + def to_python(self, value): |
| 14 | + """Convert part generator slug""" |
| 15 | + from .models import PartGenerator |
| 16 | + try: |
| 17 | + obj = PartGenerator.objects.get(slug=value) |
| 18 | + return obj |
| 19 | + except (ValueError, TypeError, ObjectDoesNotExist): |
| 20 | + raise forms.ValidationError( |
| 21 | + _("Unknown generator %(value)s"), |
| 22 | + params={'value': value}) |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +FORM_FIELD_CLASS = { |
| 28 | + BoolParam: forms.BooleanField, |
| 29 | + TextParam: forms.CharField, |
| 30 | + TextAreaParam: forms.CharField, |
| 31 | + IntegerParam: forms.IntegerField, |
| 32 | + DecimalParam: forms.DecimalField, |
| 33 | + DimmensionParam: forms.DecimalField, |
| 34 | + GeneratorParam: ForeignKeyField, |
| 35 | + FileParam: ForeignKeyField, |
| 36 | + ImageParam: ForeignKeyField, |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +def expand_name(name): |
| 41 | + """Convert param name string from 'this_is_a_name' to 'This is a name' so |
| 42 | + it can be used as the a field label |
| 43 | + |
| 44 | + Arguments: |
| 45 | + -name (string): |
| 46 | + Returns: |
| 47 | + string |
| 48 | + """ |
| 49 | + chars = '*+-_=,;.:\\/[]{}()<>#@$%&' |
| 50 | + text = name.lower() |
| 51 | + for c in chars: |
| 52 | + text = text.replace(c, ' ') |
| 53 | + text = text[0].upper() + text[1:] |
| 54 | + return text |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | +def ForeignKeyFieldFactory(param, name): |
| 59 | + """Form field factory for all params using one""" |
| 60 | + choices = param.get_choices() |
| 61 | + if choices: |
| 62 | + # Construct a query that returns the models present in choices. |
| 63 | + choices = [getattr(c, param.model_field) for c in choices] |
| 64 | + query_args = {param.model_field+'__in': choices_field} |
| 65 | + query = param.model_class.objects.filter(query_args) |
| 66 | + else: |
| 67 | + query = param.model_class.objects.all() |
| 68 | + |
| 69 | + field_args = { |
| 70 | + 'help_text': param.help_text or None, |
| 71 | + 'label': param.label or expand_name(name), |
| 72 | + 'initial': param.default, |
| 73 | + 'required': param.default is None, |
| 74 | + 'queryset': query} |
| 75 | + |
| 76 | + return forms.ModelChoiceField(**field_args) |
| 77 | + |
| 78 | + |
| 79 | +def StdFieldFactory(param, name): |
| 80 | + """Form field factory for fields using standard fields, that is: |
| 81 | + Bool, Text, TextArea, Integer, Decimal, Dimmension""" |
| 82 | + field_args = { |
| 83 | + 'help_text': param.help_text or None, |
| 84 | + 'label': param.label or expand_name(name), |
| 85 | + 'initial': param.default, |
| 86 | + 'required': param.default is None, |
| 87 | + 'validators': [ParamFormFieldValidator(param),]} |
| 88 | + |
| 89 | + # Generate correct Field type or ChoiceField |
| 90 | + choices = param.get_choices() |
| 91 | + if choices: |
| 92 | + field_args['coerce'] = param.native_type |
| 93 | + field_args['choices'] = choices |
| 94 | + field_args.pop('validators', None) |
| 95 | + return forms.TypedChoiceField(**field_args) |
| 96 | + else: |
| 97 | + return FORM_FIELD_CLASS[type(param)](**field_args) |
| 98 | + |
| 99 | + |
| 100 | +def ParamFieldFactory(param, name): |
| 101 | + field_class = FORM_FIELD_CLASS[type(param)] |
| 102 | + if field_class == ForeignKeyField: |
| 103 | + return ForeignKeyFieldFactory(param, name) |
| 104 | + else: |
| 105 | + return StdFieldFactory(param, name) |
| 106 | + |
| 107 | + |
| 108 | +class ParamInputForm(forms.Form): |
| 109 | + """ |
| 110 | + Form with fields for the parametes of a PartGenerator, can |
| 111 | + be used to validate inputs |
| 112 | + |
| 113 | + Arguments: |
| 114 | + - params: ParamDict |
| 115 | +
|
| 116 | + Examples: |
| 117 | + https://jacobian.org/writing/dynamic-form-generation/ |
| 118 | + http://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example |
| 119 | + """ |
| 120 | + def __init__(self, *args, **kwargs): |
| 121 | + """ |
| 122 | + Argument: |
| 123 | + part_gen (PartGenerator): Form's part generator instance |
| 124 | +
|
| 125 | + """ |
| 126 | + self._params = kwargs.pop('params') |
| 127 | + super(ParamInputForm, self).__init__(*args, **kwargs) |
| 128 | + |
| 129 | + # Add all visible fields from ParamDict to the form |
| 130 | + for name, param in self._params.items(): |
| 131 | + if not param.visible or not isinstance(param, Param): |
| 132 | + continue |
| 133 | + self.fields[name] = ParamFieldFactory(param, name) |
| 134 | + |
| 135 | + def clean(self): |
| 136 | + # When a form's non-string and non-required field is not supplied by |
| 137 | + # the user, None is asigned by default. Here all those fields are |
| 138 | + # removed after validation so the default value for the parameter |
| 139 | + # is used by PartGenerator. |
| 140 | + cd = dict((k, v) for k, v in self.cleaned_data.items() if v is not None) |
| 141 | + return self.cleaned_data |
| 142 | + self.cleaned_data = cd |
| 143 | + return self.cleaned_data |
| 144 | + |
| 145 | + |
0 commit comments