mike braa mike braa - 6 months ago 29
Ajax Question

using ajax for comment form, it gives me 500 internal error but without script it works which means my script is wrong;right?

I have commenting system that works(at least works in the backend). The problem is every time user submits comment the page gets refreshed. I wrote an ajax function for this, but since I'm a beginner I was expecting to get an error and I did. I got 500 internal error.I'm not sure what I did wrong though. Here;s my code

<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>


I have url like this

url(r'^comment/create/$', 'comment_create_view', name='comment_create'),


Edit:

I didn't post my views.py because it's huge, and thought I wrote ajax wrong. I'll post my view

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


I forgot to add this here

urlpatterns += patterns('comments.views',


Edit two,
the reason I'm using class for commentForAjax rather than id is because I want to have same effect for my reply-comment code too. I want one ajax function for both of my forms.

<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>


Edit:
here's my django error, I didn't know how to do it but followed daniel's guidance. is this the one?
RuntimeError at /comment/create
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 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

Answer Source

The exception you posted is quite informative:

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:

So you have to add a trailing slash to your url in the ajax method:

<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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download