I create "like button" with ajax. And i have problem with url.
When i click, i have 404: URL:http://127.0.0.1:8000/questions/get/1/%7B%%20url%20'add_like'%20%%7D
I have no idea what's wrong with this code.
Server console response this: POST /questions/get/1/%7B%%20url%20'add_like'%20%%7D HTTP/1.1" 404 3710
I added some print function at the top in my view for tests, view doesn't work.
I think problem is not complicated, but I dont see what's wrong with my urls
Maybe you can give me advice, how can i test this problem
model:
class Answer(models.Model):
text = models.TextField()
date = models.DateTimeField(default=datetime.datetime.now)
author = models.ForeignKey(CustomUser)
question = models.ForeignKey(Question)
like = models.PositiveIntegerField(default=0)
view:
def add_like(request):
if request.POST:
answer_pk = request.POST.get('answer_pk')
new_like = Answer.objects.get(pk=answer_pk)
new_like.like += 1
new_like.save()
return HttpResponse()
html in short form:
{% for answer in answers %}
<input type="button" name="{{ answer.pk }}" value="Like" class="addLike" />
{% endfor %}
ajax:
$('.addLike').click(function(){
$.ajax({
type: "POST",
url: "{% url 'add_like' %}",
data: {'answer_pk': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
});
})
and urls in short form:
project/url:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^questions/', include('apps.questions.urls')),]
apps/questions/urls
urlpatterns = [
url(r'get/(?P<question_pk>[0-9]+)/$', views.get_question, name='get_question'),
url(r'add_answer/(?P<question_pk>[0-9]+)/$', views.add_answer, name='add_answer'),
url(r'add_like/$', views.add_like, name='add_like'),]
Is your ajax included in the Django template or is it in a separate file? It looks like the URL tag {% url 'add_like' %} in your ajax code is not being converted to the actual URL by Django. Django tags only work if they are in the template. Assuming this is the problem, you could put the ajax code inside an HTML script tag inside the template so Django can convert the URL.