TTT
TTT

Reputation: 4434

Dynamic forms in Django hosted by GAE

I am a newbie to Django, GAE, and met some problems when I am trying to build some dynamic forms using Django. The idea is that the selection made from one drop-down box determines value in another field.

In detail, if an user

  1. choose "A" in "Species", then the value in the "body_weight" will be 178. Similarly,
  2. if he choose "B" in "Species", the value in "body_weight" is 1580, and
  3. if choose "C" in "Species", the he can fill in the "body_weight"

I read some examples, and found some features like "init, and super should be included". Thus I modified my codes, but it still did not work.

My problems are:

  1. What is the right position to place "init" and "super"?
  2. Do I need "self.field" here?

All suggestions are welcomed!

Thanks!

Here is the code.

Species_CHOICES=(('178','A'),('1580','B'),('','C'))

class Inp(forms.Form):
    Species = forms.ChoiceField(label='Species', choices=Species_CHOICES, initial='A')

    #Here detect the choice made by the user
    def get_STB_choices(Species):
        if Species=='178':
            r= 178
        elif Species=='1580':
            r= 1580
        else:
            r= 4440
        return a

    #assign values to a new parameter based on user's choice 
    def __init__(self, *args, **kwargs):
        super(Inp, self).__init__(*args, **kwargs)    
    body_weight=forms.FloatField(required=True, label='Body weight', initial=get_STB_choices(Species))


#write out in HTML
class InputPage(webapp.RequestHandler):
    def get(self):
        html = str(Inp())
self.response.out.write(html)

Upvotes: 1

Views: 301

Answers (1)

dragonx
dragonx

Reputation: 15143

You're going to need Javascript running on the page to update the available selections.

I implemented it one way here. Each time you make a selection, the page makes an AJAX request to get the new form fields that were dependent on the initial change.

https://github.com/dragonx/django-hier-ajax-form

After I did mine, I realized there was already an existing project that did the same thing, but our implementations are pretty different:

https://github.com/digi604/django-smart-selects

btw, I believe usually when you call super() you use it with the name of the current class, so I would have expected

super(Inp, self).__init__(*args, **kwargs)    

Upvotes: 1

Related Questions