2017-09-13 46 views
1

我使用的是django 1.10。我想知道反向函數是如何工作的。這是一個使用django的基本聊天應用程序。我停留在行號:7 index.html 以下的有文件:NoReverseMatch在/ <urls>

enter image description here

viwes.py

from django.shortcuts import render 
from django.http import HttpResponse 
from django.shortcuts import get_object_or_404 

from chat.models import ChatRoom 

def index(request): 
    chat_rooms= ChatRoom.objects.order_by('name')[:5] 
    context = { 
     'chat_list' : chat_rooms 
    } 
    return render(request,'chats/index.html', context) 


def chat_room(request,chat_room_id): 
    chat = get_object_or_404(ChatRoom, pk =chat_room_id) 
    return render(request,'chats/chat_room.html', {'chat':chat}) 

聊天/ urls.py

from django.conf.urls import url 
from django.urls import reverse 

from chat import views 

urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
    url(r'^(?P<chat_id>[0-9]+)/$', views.chat_room, name='chat_room'), 
] 

指數。 html

{% if chat_list %}</pre> 
<ul> 
    <ul>{% for chat in chat_list %}</ul> 
</ul> 
<ul> 
    <ul> 
     <li><a id="" href="{% url 'chat_room' chat.id %}"> {{ chat.name }}</a></li> 
    </ul> 
</ul> 
<ul>{% endfor %}</ul> 
<pre> 



{% else %} 

No chats are available. 

{% endif %} 

歡迎任何建議!

+1

請,加全錯誤堆棧 –

+0

你試過了哪個'url'?如果你在'localhost'運行這個,那麼'127.0.0.1:8000'應該是你的索引,'127.0.0.1:8000/id'應該是你的聊天室。 'id'應該是任何數字。沒有定義其他'url'。確保你輸入了正確的'url'。 –

+0

127.0.0.1:8000/chats/ –

回答

0

,因爲我可以在你的reeal代碼中看到你有一個錯字:

{% url 'chat_room' chat_room_id %} 
        <!-- ^^^^^^^^^^ --> 

,但在這個問題你寫的正確

{% url 'chat_room' chat.id %} 

只是把它應用到你的代碼

+0

謝謝!這是工作! –

+0

你能告訴我爲什麼是chat.id嗎? –

+0

在你的循環'聊天'這是你的模型'ChatRoom'的一個實例,所以你需要使用'ID' –