我正在用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,只是试了一下,完美的作品。如果你想留下你的评论作为答案,我会选择它作为最有帮助的。非常感谢您的帮助。 –