我正在编写一个视图,用于驱动博客文章编辑页面上的“提交”按钮。此视图将从博客文章编辑页面上的表单中捕获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))
答案 0 :(得分:2)
简单的列表理解将解决您的问题。
error_messages = {'post_title':'post title','post_text':'post text','publish':'publication status'}
errors = [error_messages[key] for key in ('post_title','post_text','publish') if not request.POST.has_key(key)]
这将为您提供错误消息名称的列表。然后,您可以编写一个错误列表,并使用错误列表决定如何处理它(例如显示所有错误,显示第一个,甚至根据丢失的数量使用消息的语法做一些奇特的逻辑)。
我可以推荐Django中的Forms对象为你做验证吗?