问题:在做插入新项目数据时,因为要回到index页面,如果把保存数据的代码写到index里,会导致刷新一次,提交一次post请求,而且如果多个页面都要post数据后回到index页面,会导致index页面很乱
解决方法:在新建项目的方法加一个if语句,如果是POST的method,就提交数据并做重定向,在方法里返回一个重定向,重定向HttpResponseRedirect是HttpResponse的子类,每个view的方法都必须返回一个Response。
from django.http import HttpResponseRedirect
def newproject(request):
if request.method == ‘POST‘ and request.POST[‘name‘] is not None: name = request.POST[‘name‘] description = request.POST[‘description‘] pmember = request.POST[‘pmember‘] devmember = request.POST[‘devmember‘] testmember = request.POST[‘testmember‘] uimember = request.POST[‘uimember‘] post = project(name=name, description=description,pmember=pmember,devmember=devmember,testmember=testmember,uimember=uimember,status="测试中") post.last_update = datetime.now() post.save() return HttpResponseRedirect(‘/index/‘) return render_to_response(‘newproject.html‘, locals(),context_instance=RequestContext(request))
时间: 2024-10-25 20:48:46