djangocheckboxdetailview

Django DetailView - display boolean from models as checkboxes


There's a number of snippets to display booleans in Django Forms as checkboxes (i.e. specifying Checkbox as a widget). For instance (assuming a boolean field defined in the model for bar):

class FooForm(forms.ModelForm):

    class Meta:
        model = Foo
        fields = ['bar'] 
        widgets = {
            'bar' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),   
        }

However I also need to display a (disabled) checkbox in DetailView (client says so). But I can't figure out an elegant way to do this, since I don't have a form meta for details view...

My current thinking is something like this (bootstrap checkbox):

<div class="form-check">
   <label class="form-check-label">
      <input type="checkbox" {% if foo.bar %}checked{% endif %} disabled>Bar
   </label>
<\div>

Any way to accomplish this in a fashion closer to the Form's widgets?


Solution

  • in the view get you form and set initial value
    get the model object and set bars initial value

    form = YourForm(initial={'bar':modelObject.bar })
    

    and then send the form to the template and simply render like form.bar you can disable this with many ways

    like

    class FooForm(forms.ModelForm):
    
        class Meta:
            model = Foo
            fields = ['bar'] 
            widgets = {
                'bar' : CheckboxInput(attrs={'class': 'required checkbox form-control','disabled':'disabled or true'}),   
            }
    

    or find and use any template filter to add attribute to form field