django 新闻编辑笔记
url(r'^news_manage/edit/$',views.news_edit,name='edit') url配置
<a href="/management/news_manage/edit/?id={{news.id}}">编辑</a>
点击后进入
<form action="{% url 'management:edit' %}?id={{ news_object.id }}" method="post">
题目:
<input type="text" name='title' value={{news_object.title }}><br>
作者:
<input type="text" name='author' value={{news_object.author }}><br>
内容:
<input type="text" name='content' style="width: 500px;height: 300px" value={{news_object.content }}><br>
是否前端显示(0不显示,1 显示):
<input type="text" name='status' value={{news_object.status }}><br>
<input type="submit" value="保存更改"/>
</form>
处理函数为:
@transaction.commit_manually
@csrf_exempt
def news_edit(request):
try:
p = News.objects.get(id=request.GET.get('id'))
if 'content' in request.POST or 'title' in request.POST or \
'status' in request.POST or 'author' in request.POST:
p.content = request.POST.get('content')
p.title = request.POST.get('title')
p.status = request.POST.get('status')
p.author = request.POST.get('author')
p.save()
transaction.commit()
return HttpResponseRedirect(reverse('management:news_manage'))
else:
transaction.commit()
return render_to_response('news/news_edit.html',
{'news_object': p}, context_instance=RequestContext(request))
except News.DoesNotExist:
transaction.rollback()
return render_to_response("error.html",
{'msg': "信息不存在"},
context_instance=RequestContext(request))
except Exception, e:
print e
transaction.rollback()
return render_to_response("error.html",
{'msg': "数据库错误"},
context_instance=RequestContext(request))
PS:render_to_response和HttpResponseRedirect区别,前者是浏览器地址栏不变在浏览器界面更改显示界面。后者是直接跳转到另一个url界面。