Django Forms: disable field if checked by booleanfield

Here is the definition of my form:

class WorkflowForm(forms.Form): new_user = forms.BooleanField(required=False) user = ModelChoiceField(queryset=User.objects.all()) description = forms.CharField(required=False, widget=forms.Textarea) 

I would like to disable the User ModelChoiceField if the new_user field is checked.

So, is it possible in this class to determine the dependence for the field on another, for example, in my case the modelchoicefield field depends on the Boolean field or not?

+4
source share
2 answers

Here's a quick downtime,

 <p>label for="id_new_user">New user:</label> <input type="checkbox" name="new_user" id="id_new_user" onclick="javascript:toggleDiv('user_choice');" checked/></p> <p id="user_choice" style="display:none"> <label for="id_user">User:</label> <select name="user" id="id_user"> <option value="" selected="selected">---------</option> <option value="1">sam</option> <option value="2">usertest</option> </select> 

forms.py

 class WorkflowForm(forms.Form): new_user = forms.BooleanField(required=False, initial=True) user = ModelChoiceField(queryset=User.objects.all()) description = forms.CharField(required=False, widget=forms.Textarea) def __init__(self, user, *args, **kwargs): super(WorkflowForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = User.objects.all() self.fields['user'].widget.attrs['style'] = 'display:none' self.fields['user'].widget.attrs['id'] = 'user_choice' self.fields['new_user'].widget.attrs['onclick'] = "javascript:toggleDiv('user_choice');" 

Patterns

 {{form.as_p}} <script> function toggleDiv(divId) { $("#"+divId).toggle(500); } </script> 
+4
source

Since your form is not ModelForm, I assume that you mean the client side: if the user checks the new user flag, the user field is disabled.

You cannot do this on the Python side, as all this happens in the browser and not on the server. You need to use javascript. An example of using jQuery:

  $(function() { $('#check').click(function() { var disable = $(this).is(':checked'); $('#choice').attr('disabled', disable); }); }); 

Good luck.

0
source

All Articles