问题描述
我正在尝试以一种模态形式实现一个表单,该表单着重于修改帖子中的评论,我所做的一切正常,问题是当我单击“提交”按钮时,它会将我发送到html中,我有模态,在那里我编辑评论。当我尝试删除将我带到表单第二页的操作表单中的url时,还会引发错误“分配之前引用的本地变量'form'”,例如,如果我在表单操作中输入登录名的URL送我到那里,但评论未更新或编辑。
我的想法很简单,当我提交表单时,模态会关闭,并且从头开始打开模态的页面就会出现,重新加载或只是显示已经编辑过的注释。
如果您需要更多信息,我可以添加它。
views.py
@need_analyst_role
def comment_modify(request,comment_id):
if 'comment_edit' in request.POST:
form_comment = FormComment(request.POST)
if form_comment.is_valid():
comment_text = form_comment.cleaned_data['text']
comment = ModelRiskTracking.objects.get(id=comment_id)
comment.comment = comment_text
print(comment.comment)
comment.save()
else:
messages.error(request,'Error!',extra_tags="danger")
context = {}
context['comment'] = ModelRiskTracking.objects.get(id=comment_id)
return render(request,'analyst_pages/comment_edit.html',context = context)
modal.html
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Editar comentario</h2>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{% url 'soc_irisk_modify' comment_id=comment.id %}" method="POST">
{% csrf_token %}
<textarea type="text" name="text" class="form-control" rows="15">{{ comment.comment|safe }}</textarea>
<div class="modal-footer">
<input type="submit" value="Actualizar" name="comment_edit" onsubmit="setFormSubmitting()" class="btn btn-info btn-sm pull-right" />
</div>
</form>
</div>
</div>
我用一个调用jQuery函数的按钮打开模态:
<script type="text/javascript">
function openModal(url){
$('#commentModal').load(url,function(){
$(this).modal('show');
});
}
</script>
<button type="button" class="btn btn-primary btn-sm pull-right" data-toggle="modal" data-target="#commentModal" onclick="openModal('{% url 'soc_comment_modify' comment_id=comment.id %}')">
解决方法
保存模型时,您需要重定向用户
@need_analyst_role
def comment_modify(request,comment_id):
if 'comment_edit' in request.POST:
form_comment = FormComment(request.POST)
if form_comment.is_valid():
comment_text = form_comment.cleaned_data['text']
comment = ModelRiskTracking.objects.get(id=comment_id)
comment.comment = comment_text
print(comment.comment)
comment.save()
return redirect("some_url")
else:
messages.error(request,'Error!',extra_tags="danger")
return redirect("some_url")
context = {}
context['comment'] = ModelRiskTracking.objects.get(id=comment_id)
return render(request,'analyst_pages/comment_edit.html',context = context)