简体   繁体   English

Django的/没有反向匹配

[英]Django no reverse match at /

I'm trying to make a picture the url to the post the picture represents, and I must be doing something wrong, but I don't know what. 我正在尝试使图片成为图片所代表帖子的网址,我必须做错了什么,但我不知道是什么。

I am getting this error when trying to visit the home page of my site. 尝试访问网站主页时出现此错误。

Error during template rendering 模板渲染期间发生错误

In template .../home.html, error at line 48 在模板... / home.html中,第48行错误

Reverse for 'view_post' with keyword arguments '{'post_id': ''}' not found. 找不到带有关键字参数'{'post_id':''}'的'view_post'。 1 pattern(s) tried: ['post/(?P[0-9]+)/$'] 尝试了1个模式:['post /(?P [0-9] +)/ $']

and the code it showcases 及其展示的代码

<a href="{% url 'view_post' post_id=post.post_id %}"><img src="media/{{ item.image }}"></a>

Also this is my view 这也是我的看法

def view_post(request, post_id):
    post = get_object_or_404(Post,id=post_id)
    return render(request,'gram/view_post.html',{'post': post})

And url 和网址

url(r'^post/(?P<post_id>[0-9]+)/$', views.view_post, name='view_post'),

Thank you for your help. 谢谢您的帮助。

I make some assumptions based on your code examples. 我根据您的代码示例做出一些假设。 This line: 这行:

post = get_object_or_404(Post,id=post_id)

says that the class Post has a property id . Post类有一个属性id However in your template you call post.post_id . 但是,您可以在模板中调用post.post_id Assuming that post is an object instance of the class Post , it should have the property id . 假设postPost类的对象实例,则它应具有属性id Probably there is no such property like post_id in the class Post . Post可能没有像post_id这样的属性。

This means that in the template post.post_id won't return an output. 这意味着在模板post.post_id不会返回输出。 Your urls, which are not shown here, expect an integer ['post/(?P[0-9]+)/$'] . 您的网址(此处未显示)应为整数['post/(?P[0-9]+)/$'] Therefore the error is thrown. 因此,将引发错误。

Try this snippet: 试试以下代码片段:

{% url 'view_post' post_id=post.id %}

and check what happens. 并检查会发生什么。

As I said, this is based on some presumptions and I don't guarantee success. 正如我所说,这是基于一些假设的,我不保证会成功。

Turned out I'm just stupid and made it hard for myself. 原来我只是愚蠢的,让我自己很难受。 The problem was I've done <a href in my home.html and home view didn't know what post.id is - obviously. 问题是我在home.html中完成了<a href并且主页视图不知道什么是post.id-显然。 The problem is fixed. 该问题已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM