2016-03-03 67 views
1

我正在學習Python/Django堆棧,通過一些培訓來構建博客。可能會讓這兩個django視圖DRY-er?

我目前有如下添加新的和編輯現有員額(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?或者長時間留下這種長度的觀點以便於閱讀更好嗎?

回答

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

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', ...] 
+1

切換到基於類的視圖不能解決重複的代碼問題。設置作者和發佈日期的代碼將被複制,除非您創建一個mixin。這不一定比Gert建議的單一功能更好。 – Alasdair

相關問題