1

I'm trying to run a test for my view and I get this error:
Django: django.urls.exceptions.NoReverseMatch: Reverse for 'create' not found. 'create' is not a valid view function or pattern name.

Here is my test:

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)

users/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 (main urls.py):

from django.urls import path, include

urlpatterns = [
    path('users/', include('users.urls', namespace='users')),
]

output of $ 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 

I believe the reverse('users:create') raises the error, and I tried a lot of things and couldn't fix it.
Please tell me how to fix it.

1 Answer 1

1

You should give the path that name:

app_name = 'users'

urlpatterns = [
    # …
    path('create/', views.create, name='create'),
    # …
]
Sign up to request clarification or add additional context in comments.

2 Comments

then it gives: ValueError: not enough values to unpack (expected 2, got 1) followed by ImportError: rest_framework doesn't look like a module path errors
@SRezaS: that is likely an additional problem in your view. The reverse one however should normally work now...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.