samedi 19 août 2017

Django Multi Checkbox form

There has to be a better way to write this code. Basically, i have a list of emails in my database. I'm struggling to make a neat form, that will have separated emails checkboxes by year and by type. For example

First year students
Checkbox Checkbox

Second year students: .......

My model looks like this

class Email(models.Model):
    name = models.CharField(max_length = 254)
    email = models.EmailField(unique = True)
    year = models.IntegerField(default=0
    course = models.IntegerField(default=0)
    type = models.CharField(max_length = 100)

And the only way currently i managed to do this by writing many forms like this

class Emailform1(forms.Form):
    my_models = forms.ModelMultipleChoiceField(
                                      widget=forms.CheckboxSelectMultiple,
                                      queryset=None)
    def __init__(self, *args, **kwargs):
        super(Emailform1, self).__init__(*args, **kwargs)
        self.fields['my_models'].queryset = Email.objects.filter(course = 1).filter(type="Type")

But this makes a big hassle working with a ton of forms in the view and etc..




Aucun commentaire:

Enregistrer un commentaire