Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms : disable field if booleanfield is checked

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 to define in this class a dependency for a field to another, like in my case a modelchoicefield depend of a booleanfield checked or not?

like image 598
user2142291 Avatar asked Oct 04 '22 19:10

user2142291


1 Answers

Here a quick simple one,

<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');"

templates

{{form.as_p}}

<script>
function toggleDiv(divId) {
    $("#"+divId).toggle(500);
}
</script>
like image 118
catherine Avatar answered Oct 12 '22 00:10

catherine