0

在 Django 中使用路径时出现错误。

这是在views.py中调用重定向函数的代码

def addmsg(request):
    c = request.POST['content']
    new_item = messageItem(content = c)
    new_item.save()
    bot_msg(c)
    return redirect('chatapp:chat')

网址.py

app_name = 'chatapp'
urlpatterns = [
    path('chat', views.chatbot, name='chat'),
    path('addmsg',views.addmsg, name='addmsg'),
    ]

Django错误:

NoReverseMatch at /addmsg
Reverse for 'chat' not found. 'chat' is not a valid view function or pattern name.
Request Method: POST
Request URL:    http://localhost:8000/addmsg
Django Version: 2.2.17
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'chat' not found. 'chat' is not a valid view function or pattern name.
Exception Location: C:\Users\xyz\Documents\Python\hotel\hotel2\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673
Python Executable:  C:\Users\xyz\Documents\Python\hotel\hotel2\env\Scripts\python.exe
Python Version: 3.9.1
Python Path:    
['C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2',
 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2\\env',
 'C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2\\env\\lib\\site-packages']
Server time:    Mon, 1 Feb 2021 18:26:38 +0000

我还在 settings.py 中注册了应用名称

4

1 回答 1

2

将redirect('chatapp:chat') 更改为redirect('chat')。

说明:重定向功能将在 urls.py 中搜索 URL 的名称,在您的情况下是

path('chat', views.chatbot, name='chat'),
于 2021-02-01T18:50:55.160 回答