Home > front end >  Saving and displaying multiple checkboxes to Django ModelMultipleChoiceField
Saving and displaying multiple checkboxes to Django ModelMultipleChoiceField

Time:03-08

I am a beginner on django 2.2 and I can't correctly send multiple choices in the database. In my field table the days are stored like this:

['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

My form :

CHOICESDAY = (("Monday", "Monday"),
                  ("Tuesday", "Tuesday"),
                  ("Wednesday", "Wednesday"),
                  ("Thursday", "Thursday"),
                  ("Friday", "Friday"),
                  ("Saturday", "Saturday"),
                  ("Sunday", "Sunday")
                  )


class FgtScheduleForm(forms.ModelForm):
    days = forms.MultipleChoiceField(required=True,
                                     choices=CHOICESDAY,
                                     widget=forms.CheckboxSelectMultiple(
                                         attrs={'class': 'checkbox-inline'}))

    class Meta:
        model = FgtSchedule
        fields = ('name','days')
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control form-form '
                         'shadow-none td-margin-bottom-5'}),
        }

    fields = ('name', 'days')

My model

class FgtSchedule(models.Model):
    days = models.CharField(max_length=100, blank=True)

My view :

def fg_schedule_list(request):
list_fg_sch = FgtSchedule.objects.all()
return render(request, 'appli/policy/fg_schedule.html',
              {'list_fg_sch': list_fg_sch})

My template

   {% for i in list_fg_sch %}
        <tr>
            <td>{{ i.id }}</td>
            <td>{{ i.name }}</td>
            <td>{{ i.days|replace_days }}</td>
        </tr>
        {% endfor %}

My custom tags :

  @register.filter
def replace_days(value):
    CHOICESDAY = {"1": "Monday",
                  "2": "Tuesday",
                  "3": "Wednesday",
                  "4": "Thursday",
                  "5": "Friday",
                  "6": "Saturday",
                  "0": "Sunday"}
    return CHOICESDAY[value]

The problem is when I want to display later all the days I have KeyError at "['1', '2']"

CodePudding user response:

The problem is that replace_days function is expecting a value like "1" and you are passing an array ['1','2']. You must to pass the values one by one or change the replace_days function.

You can change this line:

<td>{{ i.days|replace_days }}</td>

And do something like this:

<td>{% for day in i.days %}{{day|replace_days}}{% endfor %}</td>

CodePudding user response:

I found a solution on this post : https://stackoverflow.com/a/61723003/18406204

By using this extension!

I iterate like @LaCharcaSoftware said and it's working parfectly.

  • Related