0

I want to display a Form in my Django-Website

forms.py:

from django import forms

MyForm(forms.Form):
    price = forms.IntegerField()
    checkbox = forms.BooleanField()
    humidity = forms.IntegerField()
    weight = forms.IntegerField()
    amount = forms.IntegerField()

But I don't want to display the hole form. If the checkbox is checked I want to show "humidity" and "weight", else I only "amount" should be shown.

spitzbuaamy
  • 751
  • 2
  • 10
  • 25

1 Answers1

0

This might be done with javascript or it might not be.

But it CAN be done with Django.

You can override what fields are shown in form init method. And work your other conditional logic there.

Just check if form is bound and if checkbox data is available in bound data and then check/modify the fields visibility manually, by setting widget attributes or setting widget to HiddenInput.

Examples of similar questions:

Conditional field in form

django: exclude certain form elements based on a condition

http://codeinthehole.com/writing/conditional-logic-in-django-forms/

Now if you should do it in Django or in browser using scripting - It's all up to you, but while it may be easyer to do with javascript, you have to consider that you have to have validation that matches your browser side logic. For that reason i have chosen to do this always on django side and just use javascript to refresh form contents when fields values changes should trigger form contents changes.

Community
  • 1
  • 1
Odif Yltsaeb
  • 5,575
  • 12
  • 49
  • 80