django - Django 错误:NoReverseMatch at / Reverse for 'like-post' 未找到
问题描述
我正在用 Django 开发一个简单的博客。我尝试将 ajax 功能添加到我的喜欢按钮。但是得到了这个错误:
未找到参数“(”,)”的“like-post”反向。尝试了 1 种模式:['like/(?P[0-9]+)$']
PS:我按照这个视频创建了一个喜欢按钮,这个视频添加了 ajax 功能
视图.py
class PostDetailView(FormMixin, DetailView):
model = Post
form_class = CommentForm
def get_success_url(self):
return reverse('post-detail', kwargs={'pk': self.object.id})
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
postid = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = postid.total_likes()
context['form'] = CommentForm(initial={'post': self.object})
context['total_likes'] = total_likes
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
form.save()
return super(PostDetailView, self).form_valid(form)
def LikeView(request, pk):
post = Post.objects.get(id=pk)
#post = get_object_or_404(Post, id=request.POST.get('post-id'))
post.likes.add(request.user)
context = {
'post': post,
'total_likes': post.total_likes,
}
if request.is_ajax():
html = render_to_string('blogsite/like_section.html', context, request=request)
return JsonResponse({'form': html})
return HttpResponseRedirect(reverse('blogsite-home'))
网址.py
urlpatterns = [
path('', PostListView.as_view(), name='blogsite-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('like/<int:pk>', LikeView, name='like-post'),
]
base.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(event){
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like-post" post.pk %}',
data: {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'},
dataType: 'json',
success: function(response){
$('#like-section').html(response['form'])
console.log($('#like-section').html(response['form']));
},
error: function(rs, e){
console.log(rs.responseText);
}
});
});
});
</script>
like_section.html
<h5><form method="POST" action="{% url 'like-post' post.id %}">
{% csrf_token %}
<button type="submit" id="like" class="btn btn-link btn-sm" name="post-id" value="{{ post.id }}"><a href="#"><strong><i class="fa fa-thumbs-up"></i> {{ post.total_likes }}</strong></a></button><h6 align ="right" class="d-inline-block">
<a href="http://www.facebook.com/sharer/sharer.php?u=http://your-domain{{ request.get_full_path|urlencode }}"><i class="fa fa-facebook-f"></i></a> <a href="http://www.linkedin.com/shareArticle?url=http://your-domain{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://your-domain"><i class="fa fa-linkedin"></i></a>
</h6></form>
like_section.html 然后包含在我的 post_detail.html 中
<div id="like-section">
{% include 'blogsite/like_section.html' %}
</div>
我似乎无法找到解决这个问题的方法。
解决方案
如果在您尝试加载帖子详细信息视图时出现错误。您post
缺少. get_context_data
_ PostDetailView
当您尝试访问post.pk
. {% url "like-post" post.pk %}
当 Django 在上下文中找不到变量时,模板系统会插入引擎的string_if_invalid配置选项的值,默认为 ''(空字符串)。因此,url 标签会尝试查找like/<string:pk>
urls.py 中未定义的 url,从而输出错误。所以,实际上你要做的就是添加post
到context
in get_context_data
。
推荐阅读
- google-sheets - 使用 Arrayformula 查找 Google 表格
- terminal - 我在 Udacity 课程中:我试图配置我的终端,现在这个 -bash: __git_ps1: command not found...?
- javascript - 根据图像名称的搜索输入过滤数据
- javascript - A-frame 添加一个
带有实体的 onclick 事件 - c++ - va_list 和省略号之间的重载分辨率因字面值而异。为什么?
- powerbi - 使用自定义列的自定义日期过滤器
- python - pcolormesh/imshow 替代一维非等间距数组?
- java - 如何获得二维数组中的整体最大值?
- qt - 在Qt中使用'new'声明变量而不使用delete
- javascript - JQuery - 通过按回车键添加并关注下一个表单字段