仅有一条不同代码行的两个视图

时间:2020-06-03 10:58:32

标签: python django

我有两个视图,只有一行不同的代码,其余两个视图相同。如何防止代码重复?我可以删除tag_view并将可选参数作为kwarg添加到索引,并根据它返回没有特定标签或带有标签的视图吗?它应该如何工作?我的观点如下。

def index(request):
    post_form = AddPostForm(request.POST or None, instance=request.user)
    comment_form = AddCommentForm(request.POST or None, instance=request.user)
    if request.method == 'POST':
        # FORMULARZ DODAWANIA POSTU
        if post_form.is_valid():
            post_form.save()
            create_notifications(post_form.instance)

        # FORMULARZ DODAWANIA KOMENTARZA
        if comment_form.is_valid():
            comment_form.save()

    (posts, comments) = serve_post_and_comments_except_blocked(request)

    return render(request, 'mikroblog/index.html', {'posts': posts, 'comments': comments,
                                                    'post_form': post_form, 'comment_form': comment_form})


def tag_view(request, tag):
    post_form = AddPostForm(request.POST or None, instance=request.user)
    comment_form = AddCommentForm(request.POST or None, instance=request.user)
    if request.method == 'POST':
        # FORMULARZ DODAWANIA POSTU
        if post_form.is_valid():
            post_form.save()
            create_notifications(post_form.instance)

        # FORMULARZ DODAWANIA KOMENTARZA
        if comment_form.is_valid():
            comment_form.save()

    (posts, comments) = serve_post_and_comments_except_blocked(request)
    posts.filter(content_post__contains=tag)
    actual_tag = tag

    return render(request, 'mikroblog/tag.html', {'posts': posts, 'actual_tag': actual_tag, 'comments': comments,
                                                  'post_form': post_form, 'comment_form': comment_form})

1 个答案:

答案 0 :(得分:1)

我将定义一个这样的辅助函数(未经测试):

def view_common(url, request, tag=None):
    post_form = AddPostForm(request.POST or None, instance=request.user)
    comment_form = AddCommentForm(request.POST or None, instance=request.user)
    if request.method == 'POST':
        # FORMULARZ DODAWANIA POSTU
        if post_form.is_valid():
            post_form.save()
            create_notifications(post_form.instance)

        # FORMULARZ DODAWANIA KOMENTARZA
        if comment_form.is_valid():
            comment_form.save()

    (posts, comments) = serve_post_and_comments_except_blocked(request)
    posts.filter(content_post__contains=tag)

    parameters = {'posts': posts, 'comments': comments,'post_form': post_form, 'comment_form': comment_form}

    if tag:
        parameters['actual_tag'] = tag

    return render(request, url, parameters)

,然后重新定义您的2个函数,如下所示:

def tag_view(request, tag):
    return view_common('mikroblog/tag.html', request, tag=tag)

def index(request):
    return view_common('mikroblog/index.html', request)

希望这会有所帮助。