想象一下,我们有一个博客博客帖子的详细信息页面,我们接受此页面上的评论,现在我们需要知道我们正在评论的帖子,在我们的视图中,以便我们可以为该帖子制作评论对象。
如何在HiddenInput小部件值中设置{{ post.id }}
,以便我们可以在评论视图中使用它
我尝试手动将其添加到我的html表单中,但我想使用表单模板标记,以便稍后验证表单:
<input type="hidden" name="post_comment" value="{{post.id}}>
forms.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'))
答案 0 :(得分:1)
我认为您的模型Comment
与Post
具有外键关系,您可以forms.ModelChoiceField
使用comment_post
:
comment_post = forms.ModelChoiceField(queryset=Post.objects.all(),
widget=forms.HiddenInput())
在视图中,将当前帖子对象作为初始数据提供给comment_post
:
# assume you have a variable that called "current post"
comment_form = CommentForm(request.POST, initial={'comment_post': current_post})
如果您不确定行为是什么,它会创建一个隐藏的表单字段并使用current_post
预填充所选数据,然后当您发布表单时,表单已经包含数据,您可以调用comment_form.save()
即可。
答案 1 :(得分:1)
一般情况下,我会通过根据表单值以外的其他内容设置帖子ID来完成此操作。为了设置帖子评论关系,你的视图必须知道哪个帖子被评论 - 可能作为一个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中实现这个的一种方法是:
的URI:
url(r'(?P<post_id>\d+)/$', views.comment, name="comment")
根据您网址结构的其余部分,可能更清楚地包含更多上下文:
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