Re: ModelForm: Dynamically change model and fields
johan de taeye <johan.de.taeye <at> gmail.com>
2008-03-01 08:48:47 GMT
This approach works for me in a similar situation:
import new
UploadMeta = new.classobj("UploadMeta", (), {
'model': yourModel,
'fields': ('yourfield1', 'yourfield2')
})
UploadForm = new.classobj("UploadForm", (ModelForm,), {
"Meta": UploadMeta
})
In case you're wondering about the practical use case of this...
I use this to read a CSV-formatted file and validate the input rows
one by one before saving to the database.
So, when reading the header line of the file, I dynamically create the
form: the column names in the first row define the fields. For every
following line in the input file I then process it with (simplified):
try:
form = UploadForm(dictionary_built_from_the_row)
form.save()
except:
... process validation errors
My 2 cents: similar use cases for a more dynamic use of ModelForm are
sure around. It would be great if they would be supported in a cleaner
and more intuitive way than currently available.
Johan
On Feb 29, 8:47 pm, Dominik Szopa <dsz... <at> gmail.com> wrote:
> On 29 Lut, 09:28, brian <bros... <at> gmail.com> wrote:
>
>
>
>
>
> > > But this doesn't work, how to pass new _meta.fieldsand _meta.modelin
> > > init method ???
>
> > I am a bit concerned that your use-case for this kind of functionality
> > is not well justified. However, you cannotchangethefieldsin the
> > __init__ method of the form. By the time __init__ is executed the form
> > has already assembled thefields. This is done with the use of a
> > metaclass that dictates how your Form class is built. You need to do
> > some reading on metaclasses (which is an advanced Python topic) before
> > you can accomplish something like this. There can be ways to simply
> > adjust the values assigned to the class inside the class since the
> > class defintion can live anywhere, but it would be wise to understand
> > how all that works.
>
> > Again, I would seriously reconsider your approach and make sure that
> > this type of functionality is critical to your app.
>
> > Here are some handy links:
>
> >http://docs.python.org/ref/metaclasses.htmlhttp://en.wikipedia.org/wi......
>
> Thank you, i'll try to read about metaclasses, thanks for the links :)- Hide quoted text -
>
> - Show quoted text -
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users <at> googlegroups.com
To unsubscribe from this group, send email to django-users-unsubscribe <at> googlegroups.com
For more options, visit this group at http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---