Django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with arguments '('',)' not found

Why does the error message appear? I got stuck in Django Official tutorial part 5. Writing your first Django app, part 5 I understand the error message is, but I can NOT spot the cause of error. And I didn't forget to execute python manage.py makemigrations and python manage.py migrate once after I change my code. Here are commands and error messages (in conda Terminal)

(myenvtest2) C:\Users\40843\mysite>python manage.py makemigrations
No changes detected

(myenvtest2) C:\Users\40843\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  No migrations to apply.

(myenvtest2) C:\Users\40843\mysite>python manage.py test polls
404
revindex:
/polls/
Found 1 test(s).
System check identified no issues (0 silenced).
E
======================================================================
ERROR: polls.tests (unittest.loader._FailedTest.polls.tests)
----------------------------------------------------------------------
ImportError: Failed to import test module: polls.tests
Traceback (most recent call last):
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\unittest\loader.py", line 394, in _find_test_path
    module = self._get_module_from_name(name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\unittest\loader.py", line 337, in _get_module_from_name
    __import__(name)
  File "C:\Users\40843\mysite\polls\tests.py", line 59, in <module>
    response = client.get(revindex)
               ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 836, in get
    response = super().get(path, data=data, secure=secure, **extra)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 424, in get
    return self.generic(
           ^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 541, in generic
    return self.request(**r)
           ^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 810, in request
    self.check_exception(response)
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\client.py", line 663, in check_exception
    raise exc_value
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\mysite\polls\views.py", line 14, in index
    return render(request, "polls/index.html", context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\template\backends\django.py", line 62, in render
    return self.template.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\template\base.py", line 175, in render
    return self._render(context)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\test\utils.py", line 111, in instrumented_test_render
    return self.nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\template\defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\40843\.conda\envs\myenvtest2\Lib\site-packages\django\urls\resolvers.py", line 803, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with arguments '('',)' not found. 2 pattern(s) tried: ['polls/specifics/(?P<question_id>[0-9]+)/\\Z', 'polls/(?P<question_id>[0-9]+)/\\Z']


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

Here is index.html At polls\templates\polls\index.html

<!DOCTYPE html>
    <head>
        <meta charset="utf-8" />
        <title>My test page</title>
    </head>
    <body>
        <!-- 
            <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> 
        -->
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    </body>
</html>

Here is results.html At polls\templates\polls\results.html

<!DOCTYPE html>
    <head>
        <meta charset="utf-8" />
        <title>My test page</title>
    </head>
    <body>
        <p>This is my page</p>
        <h1>{{ question.question_text }}</h1>
        <ul>
        {% for choice in question.choice_set.all %}
            <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
        {% endfor %}
        </ul>
        <a href="{% url 'polls:detail' question.id %}">Vote again?</a>
    </body>
</html>

Here is test.py At polls\tests.py

from django.test import TestCase

# Create your tests here.
import datetime

from django.test import TestCase
from django.utils import timezone

from .models import Question


class QuestionModelTests(TestCase):
    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is in the future.
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

    def test_was_published_recently_with_old_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is older than 1 day.
        """
        time = timezone.now() - datetime.timedelta(days=1, seconds=1)
        old_question = Question(pub_date=time)
        self.assertIs(old_question.was_published_recently(), False)


    def test_was_published_recently_with_recent_question(self):
        """
        was_published_recently() returns True for questions whose pub_date
        is within the last day.
        """
        time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
        recent_question = Question(pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)


from django.test.utils import setup_test_environment
# setup_test_environment()
from django.test import Client
# create an instance of the client for our use
client = Client()
# get a response from '/'
response = client.get("/")
# we should expect a 404 from that address; if you instead see an
# "Invalid HTTP_HOST header" error and a 400 response, you probably
 # omitted the setup_test_environment() call described earlier.
print(response.status_code)
# on the other hand we should expect to find something at '/polls/'
# we'll use 'reverse()' rather than a hardcoded URL
from django.urls import reverse
revindex = reverse("polls:index")
print("revindex:")
print(revindex)
response = client.get(revindex)
print("response:")
print(response.status_code)
print(response.content)
print(response.context["latest_question_list"])

Here is urls.py At polls\urls.py

# availables url 
from django.urls import path

from . import views

app_name = "polls"
urlpatterns = [
    path("", views.index, name="index"),
    path("<int:question_id>/", views.detail, name="detail"),
    path("<int:question_id>/results/", views.results, name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
    path("specifics/<int:question_id>/", views.detail, name="detail"),
]

Here is polls.py At mysite\urls.py

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

app_name = "polls"

urlpatterns = [
    path("polls/", include("polls.urls")),
    path("admin/", admin.site.urls),
]

Here is setting.py At mysite\settings.py

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 4.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-(qc9la9(2tk@5o@9^@_ff$641x_@hoylx9%khhd5@z&1qjukmi"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "polls.apps.PollsConfig",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "mysite.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "mysite.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "Asia/Taipei"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

Here is my project structure. enter image description here Appreciation: Any replies or solution to this issue will be very appreciated. Thank you very much.

During trying to solve this issue, not only I have visited the Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found

but also I have checked the Django Official tutorial from part 3 to 5, checking the codes are same (I just simply follow the tutorial and copy-paste the code then execute.)

Link to Django Official tutorial from part 3 to 5.

Writing your first Django app, part 3 Writing your first Django app, part 4 Writing your first Django app, part 5

Back to Top