Ticket #5126: ticket5126_4.diff
File ticket5126_4.diff, 2.6 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, model, fields): 70 """Returns the __init__() method for a Form.""" 71 def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, 72 initial=None): 73 from django.db import models 74 if isinstance(initial, models.Model): 75 instance, initial = initial, {} 76 for f in model._meta.fields: 77 if not f.editable: 78 continue 79 if fields and f.name not in fields: 80 continue 81 initial[f.name] = f.value_from_object(instance) 82 form.__init__(self, data=data, files=files, auto_id=auto_id, 83 prefix=prefix, initial=initial) 84 return __init__ 85 57 86 def make_model_save(model, fields, fail_message): 58 87 "Returns the save() method for a Form." 59 88 def save(self, commit=True): … … 88 117 field_list.append((f.name, formfield)) 89 118 base_fields = SortedDictFromList(field_list) 90 119 return type(opts.object_name + 'Form', (form,), 91 {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')}) 120 {'base_fields': base_fields, '_model': model, 121 '__init__': make_model_init(form, model, fields), 122 'save': make_model_save(model, fields, 'created')}) 92 123 93 124 def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 94 125 """