2

it is Doctor update form with associated Clinic/Hospital list.

I want a checkbox with the M2M list of Clinic/Hospital with an individual row. here are my forms

class ClinicHospitalForm(forms.ModelForm):
 class Meta():
     model = ClinicHospital
     fields = ('name','address','contact','lat','lon')

class DoctorForm(forms.ModelForm):
class Meta():
    model = Doctor
    fields = ('name','speciality','contact','clinic_hospital')

2 Answers2

2

You can set the widget to a CheckboxSelectMultiple widget [Django-doc]:

class DoctorForm(forms.ModelForm):
    class Meta:
        model = Doctor
        fields = ('name','speciality','contact','clinic_hospital')
        widgets = {
            'clinic_hospital': forms.CheckboxSelectMultiple
        }
Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
  • it shows just checkbox. I want list along with checkbox on each row of list. – Ali Raza Javeed Jan 17 '20 at 10:39
  • @AliRazaJaveed: no normally it shows one checkbox per item (see here https://stackoverflow.com/questions/39449472/django-checkboxselectmultiple-shows-object-representation-instead-of-objects?rq=1). It looks like the css might mix it up. – Willem Van Onsem Jan 17 '20 at 10:41
  • fine when list is going long then it will look strange. – Ali Raza Javeed Jan 17 '20 at 10:42
  • @AliRazaJaveed: no, you just wrap it in a scrollable container; https://stackoverflow.com/questions/7280389/scrollable-box-containing-list-of-checkboxes-in-html – Willem Van Onsem Jan 17 '20 at 10:45
1

You can use CheckboxSelectMultiple .For example if clinic_hospital is your ManyToMany field and you want to display it as a checkbox then you can try like this

class DoctorForm(forms.ModelForm):
    clinic_hospital= forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple)
    class Meta():
       model = Doctor
       fields = ('name','speciality','contact','clinic_hospital')
Arjun
  • 5,358
  • 2
  • 7
  • 28