问题
//mytemplate//
<tr>
<td><input type="text" name="language1" id="language1" /></td>
<td><input type="checkbox" name="read1" id="read1" value="yes" /></td>
<td><input type="checkbox" name="write1" id="write1" value="yes" /></td>
<td><input type="checkbox" name="speak1" id="speak1" value="yes" /></td>
</tr>
<tr>
<td><input type="text" name="language1" id="language1" /></td>
<td><input type="checkbox" name="read1" id="read1" value="yes" /></td>
<td><input type="checkbox" name="write1" id="write1" value="yes" /></td>
<td><input type="checkbox" name="speak1" id="speak1" value="yes" /></td>
</tr>
I wanted to save yes into my db if the checkbox is checked,
If the checkbox was unchecked i want to save no into db,..
How to do it?
EDIT
def edit_other_info(request):
if request.method == "POST":
user = request.POST.get('user_id')
language1 = request.POST.get('language1')
read1 = request.POST.get('read1')
write1 = request.POST.get('write1')
speak1 = request.POST.get('speak1')
language2 = request.POST.get('language2')
read2 = request.POST.get('read2')
write2 = request.POST.get('write2')
speak2 = request.POST.get('speak2')
p=language(user_id=user,language1=language1,read1=read1,write1=write1,
speak1=speak1,language2=language2,read2=read2,write2=write2,speak2=speak2)
p.save()
return HttpResponseRedirect('/accounts/Profile/')
else:
details1 = language.objects.filter(user_id=request.user.id)
return render_to_response('registration/language.html', {"details":details, "details1":details1}, context_instance=RequestContext(request))
Thanks in advance..
回答1:
Test if the checkbox id is in the post parameters like so:
def myview(request):
if request.method == 'POST':
read1_val = "read1" in request.POST
MyModel(read1=read1_val).save()
If it is in there it was "yes". If it is not in there it was "no".
More here, here and here
回答2:
If you provide a common name to all checkboxes you could retrive the value using
options = request.POST.getlist('name')
if nothing is checked, it returns a null list.
来源:https://stackoverflow.com/questions/16147009/django-save-a-value-for-unchecked-checkbox