Adding a field to a form during runtime

126 views
Skip to first unread message

Marek W

unread,
Mar 18, 2009, 10:20:09 AM3/18/09
to django...@googlegroups.com
Hi, I would like to add a field to a form dynamically. I'm using Django 1.0.2.

Here's my view code:

class CarForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(CarForm, self).__init__(*args, **kwargs)
        self.fields['extraField'] = forms.CharField()
      
    class Meta:
        model = Car
       
class CarPhotoForm(ModelForm):
    class Meta:
        model = CarPhoto

def car(request, template_name = 'cars.html'):
    carForm = CarForm(True)
    carPhotoForm = CarPhotoForm()
    return render_to_response(template_name,  {'carForm' : carForm,  'carPhotoForm' :  carPhotoForm})


And here's  a model:

class Car(models.Model):
    car_type = models.CharField(max_length = 50)

class CarPhoto(models.Model):
    photo = models.ImageField( upload_to = 'cars_photos/')
    car = models.ForeignKey(Car)


The template is very simple too:

<h4>Car form:</h4>
<form id="carForm" method="POST" action=".">
    {{carForm.as_p}}
    <input type="Submit" value="Add car"/>
</form>
<h4>Car photo form:</h4>
<form id="carPhotoForm" method="POST" action=".">
    {{carPhotoForm.as_p}}
    <input type="Submit" value="Add photo"/>
</form>

I took this idea from http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/.  When I try to view the page, when there's my own __init__ method in CarForm class, then the car form doesn't contain any field. When i remove the __init__ method, everything works correctly.  How to add a field to a form during a runtime ?

Thanks in advance,

Marek

Thomas Guettler

unread,
Mar 18, 2009, 11:26:07 AM3/18/09
to django...@googlegroups.com
Hi,

your code looks correct.

You can try to debug it. Maybe insert
assert False, self.fields into __init__()
Do the fields from the model exist?

Thomas

Marek W schrieb:


> Hi, I would like to add a field to a form dynamically. I'm using Django
> 1.0.2.
>
> Here's my view code:
>
> class CarForm(ModelForm):
> def __init__(self, *args, **kwargs):
> super(CarForm, self).__init__(*args, **kwargs)
> self.fields['extraField'] = forms.CharField()
>
> class Meta:
> model = Car

...

> I took this idea from
> http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/. When I try to view
> the page, when there's my own __init__ method in CarForm class, then the car
> form doesn't contain any field. When i remove the __init__ method,
> everything works correctly. How to add a field to a form during a runtime ?


--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

Marek W

unread,
Mar 18, 2009, 11:52:04 AM3/18/09
to django...@googlegroups.com
Thanks for your response. Probably the reason was I didn't update a database, because now(after making syncdb) it works correctly. But by the time I've found a second problem:

while to create a dynamic form this way:

def make_car_form(extra):
    fields = { 'carType' : forms.CharField() }
    if extra:
        fields['extraField'] = forms.CharField()
    return type('ContactForm', (forms.BaseForm, ), { 'base_fields': fields })


View method:
(...)
    carForm = make_car_form(True)
(...)

then on the page there aren't any fields, whether calling make_car_form with extra=True or extra=False.

Regards,
Marek

2009/3/18 Thomas Guettler <h...@tbz-pariv.de>



--
Pozdrawiam,

Marek Wawrzyczek


Thomas Guettler

unread,
Mar 19, 2009, 8:05:44 AM3/19/09
to django...@googlegroups.com
Sorry, I can't help you here, since I don't create classes
at runtime (*). I think using __init__() is better, and I guess
you can solve your problem with it, too.

(*) type('ContactForm', (forms.BaseForm, ), { 'base_fields': fields})

Marek W schrieb:


> Thanks for your response. Probably the reason was I didn't update a
> database, because now(after making syncdb) it works correctly. But by the
> time I've found a second problem:
>
> while to create a dynamic form this way:
>
> def make_car_form(extra):
> fields = { 'carType' : forms.CharField() }
> if extra:
> fields['extraField'] = forms.CharField()
> return type('ContactForm', (forms.BaseForm, ), { 'base_fields': fields
> })
>
>
> View method:
> (...)
> carForm = make_car_form(True)
> (...)
>
> then on the page there aren't any fields, whether calling make_car_form with
> extra=True or extra=False.

Preston Timmons

unread,
Mar 19, 2009, 10:19:48 AM3/19/09
to Django users
Hi Marek,
I think that your problem is that the make_car_form function returns a
form class rather than an instance of that class. Once you have the
class you still need to make an instance of it. Something like this
might work:

form_class = make_car_form(True)
carForm = form_class()


Preston
> Thomas Guettler,http://www.thomas-guettler.de/
Reply all
Reply to author
Forward
0 new messages