假设我们有一个博客博客文章的详细信息页面,并且我们接受该页面上的评论,现在我们需要知道我们正在评论哪个帖子,以便我们可以为该帖子创建评论对象。
如何设置 {{ post.id }}
在 HiddenInput 小部件值中,以便我们可以在评论 View 中使用它
我尝试手动将其添加到我的 html 表单中,但我想使用表单模板标签,以便稍后验证表单:
<input type="hidden" name="post_comment" value="{{post.id}}>
表单.py:
comment_post = forms.Field(widget=forms.HiddenInput())
views.py:
def comment(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
Comment.objects.create(text=form.cleaned_data['comment_text'],post=form.cleaned_data['comment_post'] ,cm_author=request.user)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
最佳答案
一般来说,我会通过基于表单值以外的其他内容设置帖子 ID 来实现此目的。为了将帖子设置为评论关系,您的 View 必须知道正在评论哪个帖子(可能作为 URL 元素),所以我只是直接使用它,而不是将其作为表单数据传递。像这样的东西:
from django.shortcuts import get_object_or_404
def comment(request, post_id):
post = get_object_or_404(Post, id=post_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.post = post
new_comment.save()
# usual form boilerplate below here
在 uris.py 中实现此功能的一种方法是:
乌里斯:
url(r'(?P<post_id>\d+)/$', views.comment, name="comment")
根据 URL 结构的其余部分,包含更多上下文可能会更清晰:
url(r'post/(?P<post_id>\d+)/comment/$', views.comment, name="comment")
但这基本上取决于个人喜好,除非您的目标是 REST 风格的 API。
无需以不同方式指定表单操作 - 通常的 action=""
会将表单提交到包含 ID 的 URI,因为它是显示表单的 URI 的一部分。
如果出于某种原因您想使用隐藏输入执行此操作,请在创建表单时使用initial
参数。
if request.method == 'POST':
form = CommentForm(request.POST, initial={'comment_post': post})
# usual processing
else:
form = CommentForm(initial={'comment_post': post})
# and render
关于python - 将 django HiddenInput 小部件的值设置为模板中呈现的另一个对象的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511731/