ans2human
ans2human

Reputation: 2357

implementing checkboxes with multiple select in django admin and modelform?

i'm fairly new to django, so couldn't find a way to implement the checkboxes with multiple select in to my custom modelforms and django admin. tried the django docs but still couldnt find solution?the image is my project form wherein the technologies field should have a checkbox with multiple select. TIA

views.py

class ProjectCreate(CreateView):
model = Project
fields = ['projectid', 'title', 'description', 'startdate', 'enddate', 'cost', 'Project_type',
          'employeeid', 'technologies', 'clientid', 'document']


class ProjectUpdate(UpdateView):
model = Project
fields = ['projectid', 'title', 'description', 'startdate', 'enddate', 'cost', 'Project_type',
          'employeeid', 'technologies', 'clientid']

form-template.py

{% for fields in form %}
<div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
        <span class="text-danger small">{{ fields.errors }}</span>

    </div>
    <label class="control-label col-sm-2">{{ fields.label_tag }}</label>
    <div class="col-sm-10">{{ fields }}</div>
</div>
{% endfor %}

Upvotes: 1

Views: 3936

Answers (1)

ans2human
ans2human

Reputation: 2357

We can implement is using django-multiselectfield

  1. First install django-multiselectfield.

pip install django-multiselectfield

  1. In Models.py, we need to import multiselectfield then use MultiSelectField as modal field & pass required arguments.

    from django.db import models
    from multiselectfield import MultiSelectField
    
    MY_CHOICES = ((1, 'Value1'),
                  (2, 'Value2'),
                  (3, 'Value3'),
                  (4, 'Value4'),
                  (5, 'Value5'))
    
    #choices can be a list also
    
    class MyModel(models.Model):
    
        #....
    
        my_field = MultiSelectField(choices=MY_CHOICES,
                             max_choices=3,
                             max_length=3)
    

Now in admin panel when you open MyModel form you will see 5 check boxes out of which you can only select a maximum of 3 as defined max_choices=3

If you are rendering modelform using templates then you only need to specify the fields in Forms.py.

If you're getting dropdown data from another table then refer to this question

Upvotes: 2

Related Questions