From bdfbcb2cd51643d2d866eda8820b62521901a007 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Tue, 20 Feb 2007 02:59:16 +0000 Subject: [PATCH] Fixed #3247 -- newforms form_for_model() and form_for_instance() no longer create form fields for database fields with editable=False. Thanks for the patch, mssnlayam@yahoo.com and Philipp Keller git-svn-id: http://code.djangoproject.com/svn/django/trunk@4548 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/models.py | 8 ++++++-- tests/modeltests/model_forms/models.py | 7 +++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/django/newforms/models.py b/django/newforms/models.py index 48bf0f3d23..62b30336e3 100644 --- a/django/newforms/models.py +++ b/django/newforms/models.py @@ -34,7 +34,7 @@ def save_instance(form, instance, commit=True): raise ValueError("The %s could not be changed because the data didn't validate." % opts.object_name) clean_data = form.clean_data for f in opts.fields: - if isinstance(f, models.AutoField): + if not f.editable or isinstance(f, models.AutoField): continue setattr(instance, f.name, clean_data[f.name]) if commit: @@ -66,6 +66,8 @@ def form_for_model(model, form=BaseForm, formfield_callback=lambda f: f.formfiel opts = model._meta field_list = [] for f in opts.fields + opts.many_to_many: + if not f.editable: + continue formfield = formfield_callback(f) if formfield: field_list.append((f.name, formfield)) @@ -87,6 +89,8 @@ def form_for_instance(instance, form=BaseForm, formfield_callback=lambda f, **kw opts = model._meta field_list = [] for f in opts.fields + opts.many_to_many: + if not f.editable: + continue current_value = f.value_from_object(instance) formfield = formfield_callback(f, initial=current_value) if formfield: @@ -97,7 +101,7 @@ def form_for_instance(instance, form=BaseForm, formfield_callback=lambda f, **kw def form_for_fields(field_list): "Returns a Form class for the given list of Django database field instances." - fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list]) + fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list if f.editable]) return type('FormForFields', (BaseForm,), {'base_fields': fields}) class ModelChoiceField(ChoiceField): diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index c7ac44842a..63ec511838 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -40,10 +40,17 @@ class Writer(models.Model): class Article(models.Model): headline = models.CharField(maxlength=50) pub_date = models.DateField() + created = models.DateField(editable=False) writer = models.ForeignKey(Writer) article = models.TextField() categories = models.ManyToManyField(Category, blank=True) + def save(self): + import datetime + if not self.id: + self.created = datetime.date.today() + return super(Article, self).save() + def __str__(self): return self.headline