From c6c016a2e25777b25d1aa147b44ec0e5dc26f660 Mon Sep 17 00:00:00 2001 From: Michael Ziegler Date: Tue, 16 Feb 2010 10:18:10 +0100 Subject: [PATCH] add a PropertyModelForm that allows manipulating model's properties via a standard Django form --- pyweb/mumble/forms.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/pyweb/mumble/forms.py b/pyweb/mumble/forms.py index fd4280b..4bdb84d 100644 --- a/pyweb/mumble/forms.py +++ b/pyweb/mumble/forms.py @@ -25,6 +25,33 @@ from django.utils.translation import ugettext_lazy as _ from mumble.models import Mumble, MumbleUser +class PropertyModelForm( ModelForm ): + """ ModelForm that gets/sets fields that are not within the model's + fields as model attributes. Necessary to get forms that manipulate + properties. + """ + + def __init__( self, *args, **kwargs ): + ModelForm.__init__( self, *args, **kwargs ); + + instfields = self.instance._meta.get_all_field_names() + + for fldname in self.fields: + if fldname not in instfields: + self.fields[fldname].initial = getattr( self.instance, fldname ) + + def save( self, commit=True ): + inst = ModelForm.save( self, commit=commit ) + + instfields = inst._meta.get_all_field_names() + + for fldname in self.fields: + if fldname not in instfields: + setattr( inst, fldname, self.cleaned_data[fldname] ) + + return inst + + def populate_channel_choices( form ): """ Populate the `default channel' field's choices """ choices = [ ('', '----------') ]