我有可以运行的评论系统(至少在后端可以运行)。问题是每次用户提交评论时页面都会刷新。我为此编写了一个 ajax 函数,但由于我是初学者,所以我预计会出现错误,而我确实这样做了。我收到 500 内部错误。但我不确定我做错了什么。这是我的代码
<div class='reply_comment'>
<form method="POST" action='{% url "comment_create" %}'>{% csrf_token %}
<input type='hidden' name='post_id' id='post_id' value='{% url "comment_create" %}'/>
<input type='hidden' name='origin_path' id='origin_path' value='{{ comment.get_origin }}'/>
<input type='hidden' name='parent_id' id='parent_id' value='{{ comment.id }}' />
{% crispy comment_form comment_form.helper %}
</form>
</div>
<script>
$(document).on('submit','.commentForAjax', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/comment/create',
data:{
post_id:$('#post_id').val(),
origin_path:$('origin_path').val(),
parent_id:$('#parent_id').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
alert('it worked');
}
})
})
</script>
我有这样的网址
url(r'^comment/create/$', 'comment_create_view', name='comment_create'),
编辑:
我没有发布我的views.py,因为它太大了,并且认为我写的ajax错了。我来发表一下我的看法
def comment_create_view(request):
if request.method == "POST" and request.user.is_authenticated():
parent_id = request.POST.get('parent_id')
post_id = request.POST.get("post_id")
origin_path = request.POST.get("origin_path")
try:
post = Post.objects.get(id=post_id)
except:
post = None
parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None
if parent_comment is not None and parent_comment.post is not None:
post = parent_comment.post
form = CommentForm(request.POST)
if form.is_valid():
comment_text = form.cleaned_data['comment']
if parent_comment is not None:
# parent comments exists
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=parent_comment.get_origin,
text=comment_text,
post = post,
parent=parent_comment
)
#affected_users = parent_comment.get_affected_users()
#print "this is"
affected_users = parent_comment.get_affected_users()
return HttpResponseRedirect(post.get_absolute_url())
else:
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=origin_path,
text=comment_text,
post = post
)
return HttpResponseRedirect(post.get_absolute_url())
else:
messages.error(request, "There was an error with your comment.")
return HttpResponseRedirect(origin_path)
else:
raise Http404
我忘了在这里添加这个
urlpatterns += patterns('comments.views',
编辑两个, 我使用 class 作为 commentForAjax 而不是 id 的原因是因为我也希望我的回复评论代码具有相同的效果。我想要为我的两种表单提供一个 ajax 函数。
<div class="make_reply">
<a href='#' class='reply_btn'>reply</a>
<div class='reply_comment'>
<form method="POST" action='{% url "comment_create" %}'>{% csrf_token %}
<input type='hidden' name='post_id' id='post_id' value='{% url "comment_create" %}'/>
<input type='hidden' name='origin_path' id='origin_path' value='{{ comment.get_origin }}'/>
<input type='hidden' name='parent_id' id='parent_id' value='{{ comment.id }}' />
{% crispy comment_form comment_form.helper %}
</form>
</div>
</div>
编辑: 这是我的 django 错误,我不知道该怎么做,但遵循了丹尼尔的指导。是这个吗? /comment/create 处运行时错误 您通过 POST 调用了此 URL,但该 URL 不以斜杠结尾,并且您设置了 APPEND_SLASH。 Django 在维护 POST 数据时无法重定向到斜杠 URL。将表单更改为指向 127.0.0.1:8000/comment/create/(注意末尾的斜杠),或在 Django 设置中设置 APPEND_SLASH=False。
Request Method: POST
Request URL: http://127.0.0.1:8000/comment/create
Django Version: 1.8.4
Python Executable: env/bin/python
Python Version: 2.7.6
Python Path: [ 'env/lib/python2.7', 'env/lib/python2.7/plat-x86_64-linux-gnu', 'env/lib/python2.7/lib-tk', 'env/lib/python2.7/lib-old', 'env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', 'env/local/lib/python2.7/site-packages', 'env/lib/python2.7/site-packages']
Server time: 화요ì¼, 15 3ì›” 2016 18:48:14 +0900
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
'comments',
'notifications',
'news',
'tastypie',
'userena',
'guardian',
'easy_thumbnails',
'accounts',
'crispy_forms',
'django_select2',
'actstream',
'annoying',
'embed_video',
'ckeditor',
'ckeditor_uploader',
'whoosh',
'haystack')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
108. response = middleware_method(request)
File "env/local/lib/python2.7/site-packages/django/middleware/common.py" in process_request
84. "settings.") % (new_url[0], new_url[1]))
Exception Type: RuntimeError at /comment/create
Exception Value: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/comment/create/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
Request information:
GET: No GET data
POST:
post_id = u'/comment/create/'
csrfmiddlewaretoken = u'gw8ohxs2ZPVonPf812iM3vCAK2NnxAde'
parent_id = u'216'
FILES: No FILES data
最佳答案
您发布的异常信息非常丰富:
Exception Value: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/comment/create/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Request information:
因此,您必须在 ajax 方法中的 url 中添加尾部斜杠:
<script>
$(document).on('submit','.commentForAjax', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/comment/create/', //ADD THE SLASH!
data:{
post_id:$('#post_id').val(),
origin_path:$('origin_path').val(),
parent_id:$('#parent_id').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
alert('it worked');
}
})
})
</script>
关于javascript - 使用ajax作为评论表单,它给了我500内部错误,但没有脚本它可以工作,这意味着我的脚本是错误的;对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007466/