0

ブログ投稿編集ページで「送信」ボタンを駆動するビューを作成しています。このビューは、ブログ投稿編集ページのフォームから 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))
4

1 に答える 1

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)]

これにより、エラー メッセージ名のリストが表示されます。次に、エラー リストを取得して 1 つのエラー セクションを作成し、それをどう処理するかを決定できます (たとえば、すべてを表示するか、最初のエラーを表示するか、欠落しているエラーの数に基づいてメッセージの文法を使用して複雑なロジックを実行するなど)。

Django のFormsオブジェクトで検証を行うことをお勧めできますか?

于 2012-08-18T20:54:35.047 に答える