def edit(request, id):
post = get_object_or_404(Post, id=id)
edit_form = EditPostForm(request.POST or None, instance=post)
if edit_form.is_valid():
instance = edit_form.save(commit=False)
instance.save(update_fields=['content'])
這是我的編輯視圖來更新Post
(它只更新content
字段)。然而,Post
會保存兩次,因此在我的查詢集中顯示兩次。我在視圖代碼中存在2個保存問題,但是我怎麼會在這裏執行編輯?編輯視圖保存兩次
完整視圖:
def edit(request, id):
post = get_object_or_404(Post, id=id)
edit_form = EditPostForm(request.POST or None, instance=post)
if edit_form.is_valid():
instance = edit_form.save(commit=False)
instance.save(update_fields=['content'])
return HttpResponseRedirect('/')
else:
print(edit_form.errors)
edit_form = PostForm(instance=post)
context = {
'edit_form': edit_form,
'form_post': post
}
return render(request, 'edit.html', context)
SQL:
[11/Mar/2017 13:11:57] "GET /post/edit/192/ HTTP/1.1" 200 7394
[11/Mar/2017 13:12:08] "POST /post/edit/192/ HTTP/1.1" 302 0
[11/Mar/2017 13:12:08] "GET/HTTP/1.1" 302 0
[11/Mar/2017 13:12:08] "GET /home/ HTTP/1.1" 200 20044
EDIT
視圖
def edit(request, id):
post = get_object_or_404(Post, id=id)
print('CAT:', post.category)
edit_form = EditPostForm(request.POST or None, instance=post)
if edit_form.is_valid():
print('Edit valid')
instance = edit_form.save(commit=False)
instance.save(update_fields=['content'])
return HttpResponseRedirect('/')
else:
print('Errors:', edit_form.errors)
print('Non-field Errors:', edit_form.non_field_errors)
edit_form = PostForm(instance=post)
context = {
'edit_form': edit_form,
'form_post': post
}
return render(request, 'edit.html', context)
終端輸出時我編輯帖子:
CAT: 1
Errors:
Non-field Errors: <bound method BaseForm.non_field_errors of <EditPostForm bound=False, valid=False, fields=(content)>>
[23/May/2017 04:37:22] "GET /post/edit/37/ HTTP/1.1" 200 7430
CAT: 1
Edit valid
每次創建發表時間:
def create_post_score(sender, **kwargs):
score = PostScore.objects.create(post=kwargs['instance'])
print(score.upvotes)
post_save.connect(create_post_score, sender=Post)
通過我的一些舊的答案去,我碰到這一個。現在整理出來了嗎? – e4c5
仍然沒有排序,但是我在編輯時添加了新代碼,當我編輯帖子時顯示視圖和終端輸出。打印'CAT'兩次或非字段錯誤可能是原因,但我不確定。 – Zorgan
這裏沒有任何東西顯示模型被保存兩次。 – e4c5