lundi 22 avril 2019

Django storing multilevel check boxes value in database

This is the layout i want to be displayed when the ModelForm is rendered(crispy form).

User selects the parent checkbox (e.g. Locations 1) which will automatically select the sub check-boxes but user can deselect some check-boxes (e.g. Locations 2).

After the selection the Values of the Devices id associated with the Announcement object need to be stored in the database.

models.py

class DeviceLocation(models.Model):
    location_name = models.CharField(max_length=500)

    def __str__(self):
        return self.location_name

class Device(models.Model):
    name = models.CharField(max_length=500)
    location = models.ForeignKey(DeviceLocation, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class Announcement(models.Model):
    submitted = models.ForeignKey(User, on_delete=models.CASCADE)
    which_device= models.ForeignKey(Device, on_delete=models.CASCADE)
    ad_name = models.CharField(max_length=500)

forms.py

class AnnouncementForm(forms.ModelForm):
    which_box = forms.ModelMultipleChoiceField(
         queryset=Device.objects.all(),
         widget=forms.CheckboxSelectMultiple())

    class Meta:
        model = Announcement




Aucun commentaire:

Enregistrer un commentaire