pythondjangodjango-formsdjango-2.2multiplechoicefield

Select a valid choice. ["objects"] is not one of the available choices. in Django


I'm going to create a form where the user can select any number of objects from the options.(MultipleChoiceField)

Here are my files:

DAY_CHOICES = (
('saturday', 'شنبه'),
('sunday', 'یکشنبه'),
('monday', 'دوشنبه'),
('tuesday', 'سه شنبه'),
('wednesday', 'چهارشنبه'),
('thursday', 'پنج شنبه'),
('friday', 'جمعه'),)

# Models.py
class CorporationRequest(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=250, )
    explain = models.CharField(max_length=500, )
    assistance = models.CharField(max_length=250, choices=ASSISTANCE_CHOICES)
    days =   # MultipleChoiceField
    created_date = models.DateTimeField( auto_now_add=True)

# Forms.py
class ObjectsForm(ModelForm):
    objects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                     choices=OBJECT_CHOICES)
    class Meta:
        model = ObjectModel
        fields = '__all__'
# Views.py 
def add_corporation(request)
    if request.method == "POST":
        form = ObjectsForm(request.POST)
        if form.is_valid():
            new_corporation = form.save(commit=False)
            new_corporation.days = ','.join(form.cleaned_data['days'])
            new_corporation.save()
            return redirect('administrator:view_admin_user_corporation')
    else:
        form = ObjectsForm()
    template = 'corporation.html'
    context = {'form': form, }
    return render(request, template, context)

When I click on the submit button (for example select object 1 and 2), I get this error:

Select a valid choice. ['1', '2'] is not one of the available choices.-

Hint: each user send request to us that contain explanation and days that he can do something. So, Each user can select any day that he want.


Solution

  • If you must leave CorporationRequest.days as a CharField then you can save the day choices as a comma separated string in the field

    class CorporationRequest(models.Model):
        days = models.CharField(max_length=255)
    

    You have to clean the data coming from the multiple choice field so that it can be saved in the field

    class CorporationRequestForm(ModelForm):
        days = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                     choices=DAY_CHOICES)
        class Meta:
            model = CorporationRequest
            fields = '__all__'
    
        def clean_days(self):
            return ','.join(self.cleaned_data['days'])
    

    This will mean that CorporationRequest.days is now a string and not a list of days. You could add a method to the CorporationRequest model to return the list of days

    def get_days(self):
        return self.days.split(',')