Changeset 6627
- Timestamp:
- 10/29/07 18:52:17 (1 year ago)
- Files:
-
- django/trunk/django/newforms/models.py (modified) (10 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk/django/newforms/models.py
r5819 r6627 7 7 from django.utils.encoding import smart_unicode 8 8 9 10 9 from util import ValidationError 11 10 from forms import BaseForm, SortedDictFromList … … 18 17 ) 19 18 20 def save_instance(form, instance, fields=None, fail_message='saved', commit=True): 19 def save_instance(form, instance, fields=None, fail_message='saved', 20 commit=True): 21 21 """ 22 22 Saves bound Form ``form``'s cleaned_data into model instance ``instance``. … … 28 28 opts = instance.__class__._meta 29 29 if form.errors: 30 raise ValueError("The %s could not be %s because the data didn't validate." % (opts.object_name, fail_message)) 30 raise ValueError("The %s could not be %s because the data didn't" 31 " validate." % (opts.object_name, fail_message)) 31 32 cleaned_data = form.cleaned_data 32 33 for f in opts.fields: 33 if not f.editable or isinstance(f, models.AutoField) or not f.name in cleaned_data: 34 if not f.editable or isinstance(f, models.AutoField) \ 35 or not f.name in cleaned_data: 34 36 continue 35 37 if fields and f.name not in fields: 36 38 continue 37 f.save_form_data(instance, cleaned_data[f.name]) 38 # Wrap up the saving of m2m data as a function 39 f.save_form_data(instance, cleaned_data[f.name]) 40 # Wrap up the saving of m2m data as a function. 39 41 def save_m2m(): 40 42 opts = instance.__class__._meta … … 46 48 f.save_form_data(instance, cleaned_data[f.name]) 47 49 if commit: 48 # If we are committing, save the instance and the m2m data immediately 50 # If we are committing, save the instance and the m2m data immediately. 49 51 instance.save() 50 52 save_m2m() 51 53 else: 52 # We're not committing. Add a method to the form to allow deferred 53 # saving of m2m data 54 # We're not committing. Add a method to the form to allow deferred 55 # saving of m2m data. 54 56 form.save_m2m = save_m2m 55 57 return instance 56 58 57 59 def make_model_save(model, fields, fail_message): 58 " Returns the save() method for a Form."60 """Returns the save() method for a Form.""" 59 61 def save(self, commit=True): 60 62 return save_instance(self, model(), fields, fail_message, commit) 61 63 return save 62 64 63 65 def make_instance_save(instance, fields, fail_message): 64 " Returns the save() method for a Form."66 """Returns the save() method for a Form.""" 65 67 def save(self, commit=True): 66 68 return save_instance(self, instance, fields, fail_message, commit) 67 69 return save 68 70 69 def form_for_model(model, form=BaseForm, fields=None, formfield_callback=lambda f: f.formfield()): 71 def form_for_model(model, form=BaseForm, fields=None, 72 formfield_callback=lambda f: f.formfield()): 70 73 """ 71 74 Returns a Form class for the given Django model class. … … 88 91 field_list.append((f.name, formfield)) 89 92 base_fields = SortedDictFromList(field_list) 90 return type(opts.object_name + 'Form', (form,), 91 {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')}) 92 93 def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 93 return type(opts.object_name + 'Form', (form,), 94 {'base_fields': base_fields, '_model': model, 95 'save': make_model_save(model, fields, 'created')}) 96 97 def form_for_instance(instance, form=BaseForm, fields=None, 98 formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 94 99 """ 95 100 Returns a Form class for the given Django model instance. … … 116 121 base_fields = SortedDictFromList(field_list) 117 122 return type(opts.object_name + 'InstanceForm', (form,), 118 {'base_fields': base_fields, '_model': model, 'save': make_instance_save(instance, fields, 'changed')}) 123 {'base_fields': base_fields, '_model': model, 124 'save': make_instance_save(instance, fields, 'changed')}) 119 125 120 126 def form_for_fields(field_list): 121 "Returns a Form class for the given list of Django database field instances." 122 fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list if f.editable]) 127 """ 128 Returns a Form class for the given list of Django database field instances. 129 """ 130 fields = SortedDictFromList([(f.name, f.formfield()) 131 for f in field_list if f.editable]) 123 132 return type('FormForFields', (BaseForm,), {'base_fields': fields}) 124 133 125 134 class QuerySetIterator(object): 126 135 def __init__(self, queryset, empty_label, cache_choices): 127 self.queryset, self.empty_label, self.cache_choices = queryset, empty_label, cache_choices 136 self.queryset = queryset 137 self.empty_label = empty_label 138 self.cache_choices = cache_choices 128 139 129 140 def __iter__(self): … … 137 148 138 149 class ModelChoiceField(ChoiceField): 139 " A ChoiceField whose choices are a model QuerySet."150 """A ChoiceField whose choices are a model QuerySet.""" 140 151 # This class is a subclass of ChoiceField for purity, but it doesn't 141 152 # actually use any of ChoiceField's implementation. 153 142 154 def __init__(self, queryset, empty_label=u"---------", cache_choices=False, 143 required=True, widget=Select, label=None, initial=None, help_text=None): 155 required=True, widget=Select, label=None, initial=None, 156 help_text=None): 144 157 self.queryset = queryset 145 158 self.empty_label = empty_label … … 161 174 # self.choices is accessed) so that we can ensure the QuerySet has not 162 175 # been consumed. 163 return QuerySetIterator(self.queryset, self.empty_label, self.cache_choices) 176 return QuerySetIterator(self.queryset, self.empty_label, 177 self.cache_choices) 164 178 165 179 def _set_choices(self, value): … … 178 192 value = self.queryset.model._default_manager.get(pk=value) 179 193 except self.queryset.model.DoesNotExist: 180 raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.')) 194 raise ValidationError(ugettext(u'Select a valid choice. That' 195 u' choice is not one of the' 196 u' available choices.')) 181 197 return value 182 198 183 199 class ModelMultipleChoiceField(ModelChoiceField): 184 " A MultipleChoiceField whose choices are a model QuerySet."200 """A MultipleChoiceField whose choices are a model QuerySet.""" 185 201 hidden_widget = MultipleHiddenInput 202 186 203 def __init__(self, queryset, cache_choices=False, required=True, 187 widget=SelectMultiple, label=None, initial=None, help_text=None): 188 super(ModelMultipleChoiceField, self).__init__(queryset, None, cache_choices, 189 required, widget, label, initial, help_text) 204 widget=SelectMultiple, label=None, initial=None, 205 help_text=None): 206 super(ModelMultipleChoiceField, self).__init__(queryset, None, 207 cache_choices, required, widget, label, initial, help_text) 190 208 191 209 def clean(self, value): … … 201 219 obj = self.queryset.model._default_manager.get(pk=val) 202 220 except self.queryset.model.DoesNotExist: 203 raise ValidationError(ugettext(u'Select a valid choice. %s is not one of the available choices.') % val) 221 raise ValidationError(ugettext(u'Select a valid choice. %s is' 222 u' not one of the available' 223 u' choices.') % val) 204 224 else: 205 225 final_values.append(obj)
