我正在尝试对我的视图进行测试,但出现此错误:
Django: django.urls.exceptions.NoReverseMatch: Reverse for 'create' not found. 'create' is not a valid view function or pattern name.
这是我的测试:
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from users.models import User
class UsersTests(TestCase):
def setUp(self):
self.client = APIClient()
self.user = User.objects.create(chat_id=123456789, language='en')
def test_create_valid_user(self):
response = self.client.post(
reverse('users:create'),
data = {
'chat_id': 1234,
'language': 'en'
},
format='json'
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(User.objects.count(), 2)
用户/urls.py:
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('get-all/', views.get_all),
path('create/', views.create),
path('get-by-chat-id/<int:chat_id>/', views.get_by_chat_id),
path('update/<int:chat_id>/', views.update)
]
app/urls.py(主 urls.py):
from django.urls import path, include
urlpatterns = [
path('users/', include('users.urls', namespace='users')),
]
$ python manage.py show_urls
的输出:
/users/create/ users.views.create
/users/get-all/ users.views.get_all
/users/get-by-chat-id/<int:chat_id>/ users.views.get_by_chat_id
/users/update/<int:chat_id>/ users.views.update
我相信
reverse('users:create')
引发了错误,我尝试了很多东西但无法修复它。你应该给路径命名:
app_name = 'users'
urlpatterns = [
# ...
path('create/', views.create, name='create'),
# ...
]