0

I am trying to save the choices(options) selected by the user in the database and populate(check/select) the same using the data saved in the database.

Model:

class ScheduledEvent(models.Model):

event_id            = models.IntegerField()
project_id          = models.ForeignKey(Project, db_column = 'project_id')
start_date          = models.DateTimeField(null = False, default = timezone.now)
end_date            = models.DateTimeField(null = False, default = timezone.now)
next_scheduled_date = models.DateTimeField(default = timezone.now)
include_week_day    = models.CharField(max_length=200)
include_month_day   = models.CharField(max_length=200)

The remaining code:

weekdays=(('Mon',"Monday"),
        ('Tue','Tuesday'),
        ('Wed','Wednesday'),
        ('Thr','Thrusday'),
        ('Fri','Friday'),
        ('Sat','Saturday'),
        ('Sun','Sunday'))


class CheckBoxdays(forms.ModelForm):
    model = ScheduledEvent
    included_week_day = forms.MultipleChoiceField(choices=weekdays, widget=forms.CheckboxSelectMultiple)

The options are getting saved in the database but the choices(options) are not getting populated from the data stored in the database.

But the following code works correctly:

weekdays=(('1',"Monday"),
        ('2','Tuesday'),
        ('3','Wednesday'),
        ('4','Thrusday'),
        ('5','Friday'),
        ('6','Saturday'),
        ('7','Sunday'))

class CheckBoxdays(forms.ModelForm):
    model = ScheduledEvent
    include_week_day = forms.MultipleChoiceField(choices=weekdays, widget=forms.CheckboxSelectMultiple)

The options are populated when the first value in the choice tuple is be a single character. Am I doing something wrong here??

ashu
  • 197
  • 1
  • 10

1 Answers1

0

You have to use the Model version of the MultipleChoiceFile to do what you want to do:

class CheckBoxdays(forms.ModelForm):
    model = ScheduledEvent
    include_week_day = forms.ModelMultipleChoiceField(choices=weekdays, widget=forms.CheckboxSelectMultiple)
ger.s.brett
  • 3,267
  • 2
  • 24
  • 30
  • What exactly do you mean by "Model version of the MultipleChoiceField"? Can you elaborate/explain this? – ashu May 28 '15 at 13:30
  • you have to use the ModelMultipleChoiceField class not the MultipleChoiceField. – ger.s.brett May 28 '15 at 14:08
  • I am getting this error: 'ModelMultipleChoiceField' object has no attribute 'iterator', when I am trying to initialize the form fields with the values saved in the database. – ashu Jun 01 '15 at 06:55
  • How do you do the initialization of the form? – ger.s.brett Jun 01 '15 at 10:20