【发布时间】:2020-08-26 09:10:52
【问题描述】:
我一直在努力点赞 |不喜欢 django 上的按钮,但我遇到的问题是弹出 404 错误,因为我正在使用路径,但我正在学习的代码正在使用 url,所以有人可以帮我将这个 url 更改为路径吗?
url(r'^(?P<postid>\d+)/preference/(?P<userpreference>\d+)/$', postpreference, name='postpreference'),
我尝试将其更改为路径,但仍然没有成功
path('posts/<int:postid>/preference/<int:userpreference>', views.postpreference, name='like_post'),
现在这是应该喜欢和不喜欢的html
<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>
这是我的观点.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)
【问题讨论】:
-
你应该使用
{% url %}标签 -
您使用
image.id,而在网址中您使用post_id? -
我刚刚添加了views.py
-
@IainShelvington 如何在这个大 URL 中使用 {% url %} 标签?抱歉,我是新手。
标签: html django django-forms