Ticket #5126: ticket5126_2.diff
File ticket5126_2.diff, 2.4 KB (added by , 17 years ago) |
---|
-
django/newforms/models.py
13 13 from widgets import Select, SelectMultiple, MultipleHiddenInput 14 14 15 15 __all__ = ( 16 'save_instance', 'form_for_model', 'form_for_instance', 'form_for_fields', 17 'ModelChoiceField', 'ModelMultipleChoiceField' 16 'init_from_instance', 'save_instance', 'form_for_model', 17 'form_for_instance', 'form_for_fields', 'ModelChoiceField', 18 'ModelMultipleChoiceField' 18 19 ) 19 20 21 def init_from_instance(form, instance, fields=None): 22 """ 23 Populates the initial data of Form ``form`` from model instance 24 ``instance``. 25 """ 26 opts = instance.__class__._meta 27 for f in opts.fields: 28 if fields and f.name not in fields: 29 continue 30 form.initial[f.name] = f.value_from_object(instance) 31 20 32 def save_instance(form, instance, fields=None, fail_message='saved', commit=True): 21 33 """ 22 34 Saves bound Form ``form``'s cleaned_data into model instance ``instance``. … … 54 66 form.save_m2m = save_m2m 55 67 return instance 56 68 69 def make_model_init(form, fields): 70 """Returns the __init__() method for a Form.""" 71 def __init__(self, instance=None, **kwargs): 72 if instance: 73 opts = instance.__class__._meta 74 initial = kwargs.setdefault('initial', {}) 75 for f in opts.fields: 76 if not f.editable or f.name in initial: 77 continue 78 if fields and f.name not in fields: 79 continue 80 initial[f.name] = f.value_from_object(instance) 81 form.__init__(self, **kwargs) 82 return __init__ 83 57 84 def make_model_save(model, fields, fail_message): 58 85 "Returns the save() method for a Form." 59 86 def save(self, commit=True): … … 88 115 field_list.append((f.name, formfield)) 89 116 base_fields = SortedDictFromList(field_list) 90 117 return type(opts.object_name + 'Form', (form,), 91 {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')}) 118 {'base_fields': base_fields, '_model': model, '__init__': make_model_init(form, fields), 119 'save': make_model_save(model, fields, 'created')}) 92 120 93 121 def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 94 122 """