我正在编写一个驱动博客文章编辑页面上的“提交”按钮的视图。此视图将从博客文章编辑页面上的表单捕获 POST 数据并更新与该博客文章关联的 Post 对象。
我对 Django 相当陌生,对 Python 也不太熟悉,所以我不确定简化这个视图的最佳方法。
只是为了让这更容易理解,draft
我在编辑时称之为博客文章。我现在拥有的代码(在下面完整复制)有一系列 3 块,如下所示:
try:
new_title = request.POST['post_title']
except (KeyError):
return render_to_response('blog/edit.html', {
'draft': draft,
'error_msg': "That's weird. You didn't provide a" +
"post title in the POST arguments.",
}, context_instance=RequestContext(request))
draft.title = new_title
# Here goes some code specific to handling updating the title
如您所见,基本上,此块只是尝试获取 POST 数据,如果不能,它会重定向回编辑页面并显示错误消息。
由于该视图本质上做了 3 次相同的事情,因此违反了 DRY 原则。我正在尝试找到解决此问题的方法。将此代码分离到另一个函数的问题是错误处理过程需要向视图的调用者返回一些内容。我是否应该将它分开并检查返回值的类型?那干净吗?我不需要向函数传递大量参数吗?这被认为是不好的形式吗?
此外,如果您有任何其他提示来改进此代码的样式或设计,我将不胜感激,因为我是 Python/Django 新手。
非常感谢!
立即查看完整代码:
def save_changes(request, draft_id):
draft = get_object_or_404(Post, pk=draft_id)
# Get the new title
try:
new_title = request.POST['post_title']
except (KeyError):
return render_to_response('blog/edit.html', {
'draft': draft,
'error_msg': "That's weird. You didn't provide a" +
"post title in the POST arguments.",
}, context_instance=RequestContext(request))
draft.title = new_title
if draft.slug = None:
draft.slug = unique_slugify(draft.title)
# Get the new text
try:
new_text = request.POST['post_text']
except (KeyError):
return render_to_response('blog/edit.html', {
'draft': draft,
'error_msg': "That's weird. You didn't provide" +
"post text in the POST arguments.",
}, context_instance=RequestContext(request))
draft.text = new_text
# Get the new publication status
try:
new_published_status = request.POST['publish']
except (KeyError):
return render_to_response('blog/edit.html', {
'draft': draft,
'error_msg': "That's weird. You didn't provide a" +
"publication status in the POST arguments."
if new_published_status != draft.published:
if draft.published:
draft.published = False
draft.pub_date = None
else:
draft.published = True
draft.pub_date = timezone.now()
draft.save()
return HttpResponseRedirect(reverse('blog.views.edit', args=draft.id))