Reputation: 801
I have been trying to make a like | dislike button on django but the problem I have is that a 404 error pops up because I am using path but the code I am learning from is using url, so can someone help me changing this url to path?
url(r'^(?P<postid>\d+)/preference/(?P<userpreference>\d+)/$', postpreference, name='postpreference'),
I tryed to change it to path but still didn't worked
path('posts/<int:postid>/preference/<int:userpreference>', views.postpreference, name='like_post'),
Now this is the html that is supposed to like and dislike
<form id="likebutton" method="POST" action="/posts/{{image.id}}/preference/1/">
{% csrf_token %}
<input type="hidden">
</form>
<form id="dislikebutton" method="POST" action="/posts/{{image.id}}/preference/2/">
{% csrf_token %}
<input type="hidden">
</form>
this is my views.py
def postpreference(request, postid, userpreference):
if request.method == 'POST':
images = get_object_or_404(Post, id=postid)
obj=""
valueobj=""
try:
obj = Preference.objects.get(user=request.user, post=images)
valueobj = obj.value
userprefence = int(userprefence)
if valueobj != userprefence:
obj.delete()
upre = Preference()
upref.user = request.user
upref.post = images
upref.value = userpreference
if userpreference == 1 and valueobj != 1:
images.likes += 1
images.dislikes -= 1
elif userpreference == 2 and valueobj != 2:
images.dislikes += 1
images.likes -= 1
upref.save()
images.save()
context={'images': images, 'postid': postid}
return render (request, 'imagelist.html', context)
elif valueobj == userpreference:
obj.delete()
if userpreference == 1:
images.likes -= 1
elif userpreference == 2:
eachpost.dislikes -= 1
eachpost.save()
context= {'eachpost': eachpost, 'postid': postid}
return render (request, 'posts/detail.html', context)
except Preference.DoesNotExist:
upref= Preference()
upref.user= request.user
upref.post= images
upref.value= userpreference
userpreference= int(userpreference)
if userpreference == 1:
images.likes += 1
elif userpreference == 2:
images.dislikes +=1
upref.save()
images.save()
context= {'images': images, 'postid': postid}
return render (request, 'imagelist.html', context)
else:
images = get_object_or_404(Post, id=postid)
context= {'images': images, 'postid': postid}
return render (request, 'posts/detail.html', context)
Upvotes: 0
Views: 616
Reputation: 7744
As lain
suggested, use the URL tags instead of what you have.
From docs, the structure is as follows
{% url 'some-url-name' arg1=v1 arg2=v2 %}
So you would need something like this
<form id="likebutton" method="POST" action="{% url 'like_post' id=image.id 1/2 %}">
{% csrf_token %}
<input type="hidden">
</form>
You can see here on how you concatenate some other strings to the url.
Upvotes: 1