我正在用Django製作一個基本的博客平臺,我在編輯頁面添加了一個可以保存新編輯版本的編輯頁面,並且還添加了一個刪除選項。當單擊刪除按鈕時,會呈現一個新模板,要求確認或取消刪除。當我點擊「是」時,該帖子會根據需要自行刪除,當我點擊「否」時,它會返回到「編輯」頁面。問題是,當它返回到'編輯'頁面時,表單不再被填充,所有的字段都是空的。有沒有什麼辦法可以配置'no'選項以返回到所有填寫數據的'edit'頁面?請告知如果問題不清楚。謝謝。第二次重新生成Django表單
views.py
def edit_post(request, slug):
post=get_object_or_404(Blog, slug=slug)
form = BlogForm(request.POST or None, instance=post)
context = {
'title': post.title,
'post': post,
'form': form,
}
if 'save' in request.POST:
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(post.get_absolute_url())
elif 'delete' in request.POST:
return render(request, 'Blog/confirm-deletion.html',delete_context)
#Now delete template is shown, and view takes 'yes' or 'no' option
elif 'yes' in request.POST:
post.delete()
messages.success(request, 'Post was successfully deleted')
return HttpResponseRedirect(reverse('post_list'))
elif 'no' in request.POST:
form = BlogForm(request.POST, instance=post)
context = {
'title': post.title,
'post': post,
'form': form,
}
return render(request, 'Blog/edit_post.html', context)
#PROBLEM HERE: CAN'T GET *NO* OPTION TO RETURN TO FILLED OUT FORM PAGE
return render(request, 'Blog/edit_post.html', context)
確認,deletion.html
{% extends 'Blog/base.html' %}
{% block content %}
<form method='POST' action = '' enctype='multipart/form-data'> {% csrf_token%}
<p>Are you sure you want to delete {{title}}?</p>
<input type = 'submit' name = 'yes' value = 'Yes'/>
<input type = 'submit' name = 'no' value = 'No'/>
</form>
{% endblock %}
forms.py
從Django的進口形式 從.models導入博客
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = [
'title',
'category',
'content',
'draft'
]
當您單擊「否」,在'
@Alasdair所以重新提交到'編輯'頁面的信息來自'是/否'的形式,而不是博客形式,這就是爲什麼字段留空? –
@Alisdair,只是試了一下,完美的作品。如果你想留下你的評論作爲答案,我會選擇它作爲最有幫助的。非常感謝您的幫助。 –