Django Multiple Choice Field / Checkbox Select Multiple

前端 未结 6 1159
清酒与你
清酒与你 2020-11-29 18:09

I have a Django application and want to display multiple choice checkboxes in a user\'s profile. They will then be able to select multiple items.

This is a simplifi

6条回答
  •  遥遥无期
    2020-11-29 18:57

    The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)

    This trick works very well

    #model.py
    class ClassName(models.Model):
        field_name = models.CharField(max_length=100)
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            if self.field_name:
                self.field_name= eval(self.field_name)
    
    
    
    #form.py
    CHOICES = [('pi', 'PI'), ('ci', 'CI')]
    
    class ClassNameForm(forms.ModelForm):
        field_name = forms.MultipleChoiceField(choices=CHOICES)
    
        class Meta:
            model = ClassName
            fields = ['field_name',]
    

提交回复
热议问题