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.
If you must leave
CorporationRequest.daysas aCharFieldthen you can save the day choices as a comma separated string in the fieldYou have to clean the data coming from the multiple choice field so that it can be saved in the field
This will mean that
CorporationRequest.daysis now a string and not a list of days. You could add a method to theCorporationRequestmodel to return the list of days