【发布时间】:2014-07-22 04:26:38
【问题描述】:
我正在尝试允许用户更新模型的布尔变量,但我似乎无法将更改保存到数据库然后将更改呈现到模板。模型为“Pic”,布尔变量为“Good”。
在模板中(命名空间'single_picture'):
<form action="" method="POST">
{% csrf_token %}
{% if Pic.Good %}
<input type="submit" name="choice" id="{{ Pic.id }}" value="False" />
{% else %}
<input type="submit" name="choice" id="{{ Pic.id }}" value="True" />
{% endif %}
</form>
在应用程序的网址中:
url(r'^(?P<Pic_id>\d+)/$', views.single_picture, name='single_picture'),
在views.py中:
def single_picture(request, Pic_id):
# 'detail' in tutorial
if request.method == 'GET':
pic = get_object_or_404(Pic, pk=Pic_id)
latest_pictures_list = Pic.objects.all()
return render(request, 'pictures/single_picture.html', {'Pic': pic, 'latest_pictures_list': latest_pictures_list})
elif request.method == 'POST':
pic = get_object_or_404(Pic, pk=Pic_id)
latest_pictures_list = Pic.objects.all()
try:
pic.Good=request.POST['choice']
except (KeyError, Pic.DoesNotExist):
return render(request, 'pictures/single_picture.html', {'Pic': pic, 'error_message': 'uhhhh...',
})
else:
pic.save()
return HttpResponseRedirect(reverse('pictures:pic', pic.id))
如果我在 try: 语句结束时将 pic.Good 打印到终端,我可以看到它显示了更改后的语句,但 pic.save() 似乎没有将其保存到数据库,我也得到了
在 /pictures/4/ 处配置不正确
包含的 urlconf 4 中没有任何模式
在渲染语句中。这似乎表明项目或应用程序的网址中缺少某些内容。如何正确保存更改并呈现更改?
【问题讨论】:
标签: django python-2.7 django-views