Reputation: 33655
I have the following function, what it should do it loop the values submitted in a checkbox called groups, then submit each value to the database. However it appears to only add one value to the database. Is there anything wrong?
groups = 1,3,3,4
function UPDATED
def add_batch(request):
# If we had a POST then get the request post values.
if request.method == 'POST':
form = BatchForm(request.POST)
# Check we have valid data before saving trying to save.
if form.is_valid():
# Clean all data and add to var data.
data = form.cleaned_data
groups = data['groups'].split(",")
for item in groups:
batch = Batch(content=data['message'],
group=Group.objects.get(pk=item),
user=request.user
)
batch.save()
return redirect(batch.get_send_conformation_page())
Post vars:
groups 1, 3, 4
Form:
<form action="{% url 'add_batch' %}" method="post" class="form-horizontal" enctype="multipart/form-data" >
{% for item in groups %}
<label class="groups">
<input type="checkbox" name="groups" value="{{ item.id }}" /> {{item.name}}<br />
</label>
{% endfor %}
</form>
forms.py
class BatchForm(forms.Form):
groups = forms.CharField(max_length=100)
Upvotes: 1
Views: 604
Reputation: 11118
It looks like you have multiple checkboxes on a page and each has the name groups
. This is perfectly OK.
When you submit a form like this, the params may look like this:
?groups=1&groups=3&groups=4
Your form definition, on the other hand, is defining groups as a CharField
. It will be populated with with a value retrieved from request.GET['groups']
which will only retrieve one of the above values.
I think you would be better off if you defined groups
as:
CHOICES = (
(0, '1'),
(1, '2'),
(2, '3'),
)
class MyForm(forms.Form):
groups = forms.MultipleChoiceField(
choices=CHOICES,
label="Groups",
required=False)
Upvotes: 2