有可能让这两个django视图DRY-er?

时间:2016-03-03 11:37:48

标签: python django python-3.x django-views dry

我目前正在通过一些培训来学习Python / Django堆栈来构建博客。

我目前有两个类似的观点用于添加新帖子和编辑现有帖子(post_new和post_edit),如下所示:

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect("post_detail", pk=post.pk)      
    else:
        form = PostForm()    
    return render(request, "blog/post_edit.html", {"form": form})


def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user 
            post.published_date = timezone.now()
            post.save()
            return redirect("post_detail", pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, "blog/post_edit.html", {"form":form})

虽然这些视图执行不同的工作,但它们共享一些相同的代码。

尝试遵循最佳实践(DRY),是否有一种合理的方式来制作类似的观点DRYer?或者以较长的形式留下这种长度的视图以使其易于阅读?

2 个答案:

答案 0 :(得分:4)

我个人会这样写:

def post_edit(request, pk=None):
    if pk is not None:
        post = get_object_or_404(Post, pk=pk)
    else:
        post = None
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user 
            post.published_date = timezone.now()
            post.save()
            return redirect("post_detail", pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, "blog/post_edit.html", {"form":form})

基本上,您将默认instance值传递给ModelForm

答案 1 :(得分:0)

您可能希望使用Class-based views

from django.views.generic.edit import CreateView, UpdateView

class PostCreate(CreateView):
    model = Post
    fields = ['name', ...]

class PostUpdate(UpdateView):
    model = Post
    fields = ['name', ...]