我有以下功能,它應該做什麼循環在一個名爲groups的複選框中提交的值,然後將每個值提交給數據庫。但是它似乎只向數據庫添加一個值。有什麼不對的嗎?循環複選框並非所有值都添加到數據庫中
基團= 1,3,3,4-
功能修訂
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變量:
groups 1, 3, 4
形式:
<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)
請不要用'的項目範圍(LEN(組))'。 '對於組中的項目'更清晰,那麼'item'就是你需要的實際對象。 – 2013-03-21 10:18:31
你可以發佈你的Django表單嗎? – Vincent 2013-03-21 10:20:26
@Daniel for groups給我的列表索引必須是整數,而不是unicode – Prometheus 2013-03-21 10:48:07