有人可以说我错了吗?我想在成功添加后用ajax更新评论列表,但最后看到这个页面。
新评论在数据库中,但似乎我想念一些东西。提交后,它将我重定向到“task_comment_add”网址,但我需要保持在同一页面只更新对象列表(任务 - 评论)。
urls.py:
url(r'^(?P<project_code>[0-9a-f-]+)/(?P<group_task_code>[0-9a-f-]+)/(?P<task_code>[0-9a-f-]+)/task_comment_add/$',
task_comment_add,
name='task_comment_add'),
views.py:
def task_comment_add(request, project_code, group_task_code, task_code):
data = dict()
project = get_object_or_404(Project, pk=project_code, status='open')
group_task = get_object_or_404(GroupTask, pk=group_task_code)
task = get_object_or_404(Task, pk=task_code)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.save()
task.comments.add(comment)
data['form_is_valid'] = True
data['html_task_comment'] = render_to_string('project/task_comment_list.html',
{'task': task})
else:
data['form_is_valid'] = False
else:
form = CommentForm()
context = {'project': project, 'group_task': group_task, 'task': task, 'form': form}
data['html_task_comment_form'] = render_to_string('project/task_comment_form.html', context, request=request)
return JsonResponse(data)
task_list.html:
<div class="list-group custom-list-group">
<div class="list-group-item bg-faded">
{% include 'project/task_comment_form.html' %}
</div>
<div id="task-comments">
{% include 'project/task_comment_list.html' %}
</div>
</div>
task_comment_form.html:
<form method="post" id="task-comment-form" action="{% url 'project:task_comment_add' project_code=project.code group_task_code=group_task.code task_code=task.code %}">
</form>
task_comment_list.html:
{% for comment in task.comments.all %}
<div class="list-group-item flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h6 class="mb-1">{{ comment.author }}</h6>
<small>{{ comment.created }}</small>
</div>
<p class="custom-p">{{ comment.text }}</p>
</div>
{% empty %}
<div class="list-group-item flex-column align-items-start">
<div class="d-flex w-100 justify-content-center">
<h6 class="mb-1 custom-h"><i class="fa fa-info-circle" aria-hidden="true"></i>	{% trans 'NO COMMENTS' %}</h6>
</div>
</div>
{% endfor %}
JS:
$("#task-comment-form").submit(function(event) {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#task-comments").html(data.html_task_comment);
}
else {
$("#task-comment-form").html(data.html_task_comment_form);
}
}
});
$("#task-comment-form")[0].reset();
return false;
});