django forms : disable field if booleanfield is checked

  • Last Update :
  • Techknowledgy :

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>

You can't do that on the side of Python, as it's all happening in the browser, and not on the server. You need to use javascript. Example using jQuery:

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

Suggestion : 2

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.,The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form.,Widgets of required form fields have the required HTML attribute. Set the Form.use_required_attribute attribute to False to disable it. The required attribute isn’t included on forms of formsets because the browser validation may not be correct when adding and deleting formsets.,When using the RadioSelect widget, this optional boolean argument determines whether an empty choice is created. By default, blank is False, in which case no empty choice is created.

>>> from django
import forms
   >>>
   f = forms.EmailField() >>>
   f.clean('foo@example.com')
'foo@example.com' >>>
f.clean('invalid email address')
Traceback(most recent call last):
   ...
   ValidationError: ['Enter a valid email address.']
>>> from django
import forms
   >>>
   f = forms.CharField() >>>
   f.clean('foo')
'foo' >>>
f.clean('')
Traceback(most recent call last):
   ...
   ValidationError: ['This field is required.'] >>>
   f.clean(None)
Traceback(most recent call last):
   ...
   ValidationError: ['This field is required.'] >>>
   f.clean(' ')
' ' >>>
f.clean(0)
'0' >>>
f.clean(True)
'True' >>>
f.clean(False)
'False'
>>> f = forms.CharField(required = False) >>>
   f.clean('foo')
'foo' >>>
f.clean('')
'' >>>
f.clean(None)
'' >>>
f.clean(0)
'0' >>>
f.clean(True)
'True' >>>
f.clean(False)
'False'
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(label='Your name')
... url = forms.URLField(label='Your website', required=False)
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr>
   <th>Your name:</th>
   <td><input type="text" name="name" required></td>
</tr>
<tr>
   <th>Your website:</th>
   <td><input type="url" name="url"></td>
</tr>
<tr>
   <th>Comment:</th>
   <td><input type="text" name="comment" required></td>
</tr>
>>> class ContactForm(forms.Form):
... age = forms.IntegerField()
... nationality = forms.CharField()
... captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
>>> f = ContactForm(label_suffix='?')
>>> print(f.as_p())
<p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required></p>
<p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required></p>
<p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required></p>
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr>
   <th>Name:</th>
   <td><input type="text" name="name" value="Your name" required></td>
</tr>
<tr>
   <th>Url:</th>
   <td><input type="url" name="url" value="http://" required></td>
</tr>
<tr>
   <th>Comment:</th>
   <td><input type="text" name="comment" required></td>
</tr>

Suggestion : 3

As your form is not a ModelForm, I assume what you mean is client side: if the user checks the new user checkbox, the user field becomes disabled.,Django Forms : disable field if booleanfield is checked,How to disable client-side form field validation in Django admin,Make a field required if another field is checked in Django form

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>

You can't do that on the side of Python, as it's all happening in the browser, and not on the server. You need to use javascript. Example using jQuery:

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

Suggestion : 4

Last Updated : 13 Feb, 2020

Syntax

field_name = forms.BooleanField( ** options)

Let’s run the server and check what has actually happened, Run

Python manage.py runserver

Let’s run the server and check what has actually happened, Run

Python manage.py runserver

Suggestion : 5

Works just like BooleanField but also allows "Unknown" value; returns None when the Unknown(1) value is selected, True when the Yes(2) value is selected and False when the No(3) value is selected.,Generates HTML checkbox input markup to obtain a boolean True or False value; returns False when the checkbox is unchecked, True when the checkbox is checked.,Works just like CharField, but server-side Django validates the (text) value is convertable to a UUID (Universally unique identifier).,Generates an HTML select list for multiple values from tuple of tuples defined through choices (e.g.((1,'United States'),(2,'Canada'),(3,'Mexico'))). It works just like ChoiceField but allows multiple values to be selected, which become available as a list in post-processing.

<input type='checkbox' ...>
<select>
   <option value="1" selected="selected">
      Unknown
   </option>
   <option value="2">
      Yes
   </option>
   <option value="3">
      No
   </option>
</select>
<input type="text" ...>
<input type="email" ...>
<input type="url" ...>
<select>
   <option value="directory/file_1">
      file_1
   </option>
   <option value="directory/file_2">
      file_2
   </option>
   <option value="directory/file_3">
      file_3
   </option>
</select>

Suggestion : 6

django.db.models.BooleanField() , django.forms.CharField() , django.db.models.TextField() , django.forms.ModelForm()

def __init__(self, league, player, * args, ** kwargs):
   super(NotificationsForm, self).__init__( * args, ** kwargs)
for type_, _ in PLAYER_NOTIFICATION_TYPES:
   setting = PlayerNotificationSetting.get_or_default(player = player, league = league,
      type = type_)
self.fields[type_ + "_lichess"] = forms.BooleanField(required = False, label = "Lichess",
   initial = setting.enable_lichess_mail)
self.fields[type_ + "_slack"] = forms.BooleanField(required = False, label = "Slack",
   initial = setting.enable_slack_im)
self.fields[type_ + "_slack_wo"] = forms.BooleanField(required = False,
   label = "Slack (with opponent)",
   initial = setting.enable_slack_mpim)
if type_ == 'before_game_time':
   offset_options = [(5, '5 minutes'), (10, '10 minutes'), (20, '20 minutes'),
      (30, '30 minutes'), (60, '1 hour'), (120, '2 hours')
   ]
self.fields[type_ + '_offset'] = forms.TypedChoiceField(choices = offset_options,
   initial = int(
      setting.offset.total_seconds()) / 60,
   coerce = int)
def set_choices(self, family):
   # There 's probably a better way of doing this
board_choices = [(brd.id, brd.name) for brd in Board.objects.filter(family = family)]

self.fields['board_type'].choices = board_choices

# class GuidedDeviceFlashForm(forms.Form):
   # DEVICE_FAMILY_CHOICES = GuidedDeviceSelectForm.DEVICE_FAMILY_CHOICES
#
# device_family = forms.ChoiceField(label = "Device Family",
   # widget = forms.Select(attrs = {
      'class': 'form-control',
      # 'data-toggle': 'select'
   }),
   # choices = DEVICE_FAMILY_CHOICES, required = True)
# should_flash_device = forms.BooleanField(widget = forms.HiddenInput, required = False, initial = False)
#
#
def get_field_kind(field):
   if field['kind'] == 'string':
   return forms.CharField(max_length = 255, required = False)
elif field['kind'] == 'email':
   return forms.EmailField(max_length = 255, required = False)
elif field['kind'] == 'integer':
   return forms.IntegerField(required = False)
elif field['kind'] == 'boolean':
   return forms.BooleanField(required = False)
elif field['kind'] == 'text':
   return forms.CharField(widget = forms.Textarea(), required = False)
elif field['kind'] == 'choice':
   return forms.ChoiceField(choices = map(lambda c: (c, c), field['choices']))
elif field['kind'] == 'timezones':
   return TimezoneField()
elif field['kind'] == 'authentication':
   return SwitchField('user', 'service', required = True)
elif field['kind'] == 'json':
   return JsonField(required = False)
elif field['kind'] == 'integer_list':
   return CommaSeparatedIntegerField(required = False)
elif field['kind'] == 'string_list':
   return CommaSeparatedCharField(required = False)
else:
   return forms.CharField(max_length = 255, required = False)
def to_python(self, value):
   ""
"Returns a Python boolean object.

It is necessary to customize the behavior because the
default ``
BooleanField``
treats the string '0'
as ``
False``, but
if the
unit is in ``
UNTRANSLATED``
state(which would report '0'
   as a value), we need the marked checkbox to be evaluated as ``
True``.

: return: ``
False``
for any unknown: cls: `~pootle_store.models.Unit`
states and
for the 'False'
string.
""
"
truthy_values = (str(s) for s in (UNTRANSLATED, FUZZY, TRANSLATED))
if isinstance(value, str) and(
      value.lower() == "false"
      or value not in truthy_values
   ):
   value = False
else:
   value = bool(value)

return super().to_python(value)
def __init__(self, * args, ** kwargs):
   super().__init__( * args, ** kwargs)
field_order = [
   "virtual_server", "name",
   "allow_pairing", "is_supervised", "is_mandatory", "is_mdm_removable",
   "await_device_configured", "auto_advance_setup",
   "support_phone_number", "support_email_address",
   "org_magic", "department", "include_tls_certificates"
]
for pane, initial in self.Meta.model.SKIPPABLE_SETUP_PANES:
   if self.instance.pk:
   initial = pane in self.instance.skip_setup_items
self.fields[pane] = forms.BooleanField(label = "Skip {} pane".format(pane), initial = initial, required = False)
field_order.append(pane)
field_order.extend(["realm", "use_realm_user", "realm_user_is_admin",
   "admin_full_name", "admin_short_name", "admin_password"
])
self.order_fields(field_order)
def __init__(self, extension, * args, ** kwargs):
   self.extension = extension
kwargs.setdefault('label', extension.name)
ext = profile.extensions.get(self.extension.key)
if ext:
   ext = ext.serialize()
kwargs.setdefault('initial', [ext['value'], ext['critical']])

fields = (
   forms.MultipleChoiceField(required = False, choices = extension.CHOICES),
   forms.BooleanField(required = False),
)

widget = MultiValueExtensionWidget(choices = extension.CHOICES)
super(MultiValueExtensionField, self).__init__(
   fields = fields, require_all_fields = False, widget = widget,
   * args, ** kwargs)

Suggestion : 7

The default widget for this input is the CheckboxInput. The boolean field in Django form is a checkbox field that stores either True or False value. The empty value is False by default. It normalizes to a Python True or False value.,In this blog, we will check different CheckboxInput Django form fields(BooleanField) with examples.,Different types of CheckboxInput Django form fieldsBooleanField,The fields of the form are classes themselves; They manage form data and perform validation when a form is submitted.

Example:

class CheckBoxInputForm(forms.Form):
   is_valid = forms.BooleanField(label = 'Is Valid', label_suffix = " : ",
      required = True, disabled = False,
      widget = forms.widgets.CheckboxInput(attrs = {
         'class': 'checkbox-inline'
      }),
      help_text = "Please check the box as this field is required.",
      error_messages = {
         'required': "Please check the box"
      })

Suggestion : 8

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.,Django 1.9 added the Field.disabled attribute:,Get monthly updates about new articles, cheatsheets, and tricks.

And so you only need to do:

MyChangeForm(ModelForm):

def __init__(self, *args, **kwargs):
super(MyChangeForm, self).__init__(*args, **kwargs)
self.fields['<field_to_disable>'].disabled = True

And creating the form you need:

MyChangeForm(initial={'<field_to_disable>': "something"})

Before version 1.9 you had to:

class MyChangeForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.id:
self.fields['<field_to_disable>'].required = False
   self.fields['<field_to_disable>'].widget.attrs['disabled'] = True

      def clean_<field_to_disable>(self):
         # As shown in the above answer.
         instance = getattr(self, 'instance', None)
         if instance:
         return instance.<field_to_disable>
            else:
            return self.cleaned_data.get('<field_to_disable>', None)