# NameError: name 'TestCase' is not defined

**URL:** <https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635>\
**Category:** Getting Started\
**Created:** [November 25, 2023, 6:01am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635 "2023-11-25T06:01:54Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [November 25, 2023, 6:01am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/1 "2023-11-25T06:01:54Z")

</div>

In “Writing your first Django app, part 6”, when attempting to run the server, I get the following error:

```auto
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 980, in _bootstrap_inner
    self.run()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 485, in check
    all_issues = checks.run_checks(
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 494, in check
    for pattern in self.url_patterns:
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance. __dict__ [self.name] = self.func(instance)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)     
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance. __dict__ [self.name] = self.func(instance)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\importlib\ __init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked        
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed      
  File "D:\DjangoTutorial1Attempt2\mysite\mysite\urls.py", line 21, in <module>     
    path("polls/", include("polls.urls")),
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\importlib\ __init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked        
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed      
  File "D:\DjangoTutorial1Attempt2\mysite\polls\urls.py", line 3, in <module>       
    from . import views
  File "D:\DjangoTutorial1Attempt2\mysite\polls\views.py", line 94, in <module>     
    class QuestionIndexViewTests(TestCase):
NameError: name 'TestCase' is not defined

```

Here is my tests.py file:

```auto
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):
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

class QuestionDetailViewTests(TestCase):
    def test_future_question(self):
        future_question = create_question(question_text="Future question.", days=5)
        url = reverse("polls:detail", args=(future_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_past_question(self):
        past_question = create_question(question_text="Past Question.", days=-5)
        url = reverse("polls:detail", args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)

```

Here is my views.py file:

```auto
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.template import loader
from django.views import generic
from django.utils import timezone

from .models import Choice, Question

class IndexView(generic.ListView):
    template_name = "polls/index.html"
    context_object_name = "latest_question_list"

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by("-pub_date")[:5]
    
class DetailView(generic.DetailView):
    model = Question
    template_name = "polls/detail.html"

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    model = Question
    template_name = "polls/results.html"

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    context = {"latest_question_list": latest_question_list}
    return render(request, "polls/index.html", context)

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    template = loader.get_template("polls/index.html")
    context = {
        "latest_question_list": latest_question_list,
    }
    return HttpResponse(template.render(context, request))

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    output = ", ".join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/detail.html", {"question": question})

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/results.html", {"question": question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST["choice"])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(
            request,
            "polls/detail.html",
            {
                "question": question,
                "error_message": "You didn't select a choice.",
            },
        )
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, "polls/detail.html", {"question": question})

def create_question(question_text, days):
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)

class QuestionIndexViewTests(TestCase):
    def test_no_questions(self):
        response = self.client.get(reverse("polls:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No polls are available.")
        self.assertQuerySetEqual(response.context["latest_question_list"], [])

    def test_past_question(self):
        question = create_question(question_text="Past question.", days=-30)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["latest_question_list"], [question],)

    def test_future_question(self):
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse("polls:index"))
        self.assertContains(response, "No polls are available.")
        self.assertQuerySetEqual(response.context["latest_question_list"], [])

    def test_future_question_and_past_question(self):
        question = create_question(question_text="Past question.", days=-30)
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["latest_question_list"], [question],)

    def test_two_past_questions(self):
        question1 = create_question(question_text="Past question 1.", days=-30)
        question2 = create_question(question_text="Past question 2.", days=-5)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["latest_question_list"], [question2, question1],)

```

And here is my index.html:

```auto
{% load static %}

<link rel="stylesheet" href=""{% static 'polls/style.css' %}">

{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
    <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

```

---

<div class="post-metadata">

**Author:** ![taeyoung1005](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/taeyoung1005/32/17285_2.png) [@taeyoung1005](https://forum.djangoproject.com/u/taeyoung1005)\
**Post date:** [November 25, 2023, 10:02am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/2 "2023-11-25T10:02:06Z")

</div>

> [@Alex-King-1998](#):
>
> `class QuestionIndexViewTests(TestCase):`

you should import TestCase in views.py

class QuestionIndexViewTests(TestCase): → error

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 25, 2023, 11:51am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/3 "2023-11-25T11:51:19Z")

</div>

Your test cases do not belong in the views.py file. They belong _only_ in the tests file.

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [November 26, 2023, 12:05am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/4 "2023-11-26T00:05:03Z")

</div>

Ok, I moved the tests to tests.py. Still getting the same error.

Here is my tests.py now:

```auto
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):
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

class QuestionDetailViewTests(TestCase):
    def test_future_question(self):
        future_question = create_question(question_text="Future question.", days=5)
        url = reverse("polls:detail", args=(future_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_past_question(self):
        past_question = create_question(question_text="Past Question.", days=-5)
        url = reverse("polls:detail", args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)

class QuestionIndexViewTests(TestCase):
    def test_no_questions(self):
        response = self.client.get(reverse("polls:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No polls are available.")
        self.assertQuerySetEqual(response.context["latest_question_list"], [])

    def test_past_question(self):
        question = create_question(question_text="Past question.", days=-30)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["latest_question_list"], [question],)

    def test_future_question(self):
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse("polls:index"))
        self.assertContains(response, "No polls are available.")
        self.assertQuerySetEqual(response.context["latest_question_list"], [])

    def test_future_question_and_past_question(self):
        question = create_question(question_text="Past question.", days=-30)
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["latest_question_list"], [question],)

    def test_two_past_questions(self):
        question1 = create_question(question_text="Past question 1.", days=-30)
        question2 = create_question(question_text="Past question 2.", days=-5)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["latest_question_list"], [question2, question1],)

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 26, 2023, 12:48am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/5 "2023-11-26T00:48:30Z")

</div>

Please post the complete error with the traceback.

If you’re getting _exactly_ the same error, then no, you didn’t do what you thought you did.

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [November 26, 2023, 12:51am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/6 "2023-11-26T00:51:15Z")

</div>

Here is the updated error:

```auto
PS D:\DjangoTutorial1Attempt2\mysite> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 980, in _bootstrap_inner
    self.run()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 485, in check
    all_issues = checks.run_checks(
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 494, in check
    for pattern in self.url_patterns:
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance. __dict__ [self.name] = self.func(instance)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)     
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance. __dict__ [self.name] = self.func(instance)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\importlib\ __init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked        
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed      
  File "D:\DjangoTutorial1Attempt2\mysite\mysite\urls.py", line 21, in <module>     
    path("polls/", include("polls.urls")),
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\importlib\ __init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked        
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed      
  File "D:\DjangoTutorial1Attempt2\mysite\polls\urls.py", line 3, in <module>       
    from . import views
  File "D:\DjangoTutorial1Attempt2\mysite\polls\views.py", line 94, in <module>     
    class QuestionIndexViewTests(TestCase):
NameError: name 'TestCase' is not defined

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 26, 2023, 12:51am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/7 "2023-11-26T00:51:48Z")

</div>

Please post your view.py file.

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [November 26, 2023, 12:55am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/8 "2023-11-26T00:55:42Z")

</div>

```auto
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.template import loader
from django.views import generic
from django.utils import timezone

from .models import Choice, Question

class IndexView(generic.ListView):
    template_name = "polls/index.html"
    context_object_name = "latest_question_list"

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by("-pub_date")[:5]
    
class DetailView(generic.DetailView):
    model = Question
    template_name = "polls/detail.html"

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    model = Question
    template_name = "polls/results.html"

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    context = {"latest_question_list": latest_question_list}
    return render(request, "polls/index.html", context)

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    template = loader.get_template("polls/index.html")
    context = {
        "latest_question_list": latest_question_list,
    }
    return HttpResponse(template.render(context, request))

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    output = ", ".join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/detail.html", {"question": question})

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/results.html", {"question": question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST["choice"])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(
            request,
            "polls/detail.html",
            {
                "question": question,
                "error_message": "You didn't select a choice.",
            },
        )
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, "polls/detail.html", {"question": question})

def create_question(question_text, days):
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)

```

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [November 30, 2023, 7:43am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/9 "2023-11-30T07:43:56Z")

</div>

Still looking for an answer to this. I’m not sure why it’s returning “TestCase is not defined” when I already added the import TestCase at the top of tests.py.

I am also baffled as to why it’s referencing the error to line 94 of views.py, which is an empty line.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 30, 2023, 1:14pm UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/10 "2023-11-30T13:14:11Z")

</div>

Something doesn’t match up here.

You’re either not running the code that you think you’re running, or you’re not editing the code that is running.

Is the `views.py` file you posted here the file at?:

> [@Alex-King-1998](#):
>
> `"D:\DjangoTutorial1Attempt2\mysite\polls\views.py"`

Because there is no line:

> [@Alex-King-1998](#):
>
> `class QuestionIndexViewTests(TestCase):`

in the file you’re showing.

---

<div class="post-metadata">

**Author:** ![AhmdMWddh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmdmwddh/32/21707_2.png) [@AhmdMWddh](https://forum.djangoproject.com/u/AhmdMWddh)\
**Post date:** [November 30, 2023, 7:19pm UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/11 "2023-11-30T19:19:27Z")

</div>

> [@Alex-King-1998](#):
>
> ```auto
> class QuestionModelTests(TestCase):
> def test_was_published_recently_with_future_question(self):
> time = timezone.now() + datetime.timedelta(days=30)
> future_question = Question(pub_date=time)
> self.assertIs(future_question.was_published_recently(), False)
> 
> class QuestionDetailViewTests(TestCase):
> def test_future_question(self):
> future_question = create_question(question_text="Future question.", days=5)
> url = reverse("polls:detail", args=(future_question.id,))
> response = self.client.get(url)
> self.assertEqual(response.status_code, 404)
> 
> def test_past_question(self):
> past_question = create_question(question_text="Past Question.", days=-5)
> url = reverse("polls:detail", args=(past_question.id,))
> response = self.client.get(url)
> self.assertContains(response, past_question.question_text)
> 
> ```

I guess the Classes Also should start with **Test** prefix, Worth Trying.  
**Example:**

```auto
class TestQuestionModelTests(TestCase):
    def test_was_published_recently_with_future_question(self):
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

class TestQuestionDetailViewTests(TestCase):
    def test_future_question(self):
        future_question = create_question(question_text="Future question.", days=5)
        url = reverse("polls:detail", args=(future_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_past_question(self):
        past_question = create_question(question_text="Past Question.", days=-5)
        url = reverse("polls:detail", args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)

```

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [December 1, 2023, 6:51am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/12 "2023-12-01T06:51:37Z")

</div>

@KenWhitesell that’s because I moved it to the tests file.

@AhmdMWddh tried that, no dice.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 1, 2023, 12:44pm UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/13 "2023-12-01T12:44:13Z")

</div>

Then please post the complete traceback from your most recent attempt, because you cannot be getting _that_ same exact error from the file you’re showing here.

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [December 2, 2023, 5:34am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/14 "2023-12-02T05:34:24Z")

</div>

Ok, just to make sure, I closed the server and ran it again, and here is the updated error:

```auto
PS D:\DjangoTutorial1Attempt2\mysite> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 980, in _bootstrap_inner
    self.run()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run     
    self.check(display_num_errors=True)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 485, in check
    all_issues = checks.run_checks(
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 494, in check
    for pattern in self.url_patterns:
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance. __dict__ [self.name] = self.func(instance)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance. __dict__ [self.name] = self.func(instance)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\importlib\ __init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module    
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "D:\DjangoTutorial1Attempt2\mysite\mysite\urls.py", line 21, in <module>
    path("polls/", include("polls.urls")),
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\importlib\ __init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module    
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "D:\DjangoTutorial1Attempt2\mysite\polls\urls.py", line 3, in <module>
    from . import views
  File "D:\DjangoTutorial1Attempt2\mysite\polls\views.py", line 94, in <module>
    class QuestionIndexViewTests(TestCase):
NameError: name 'TestCase' is not defined

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 2, 2023, 5:47am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/15 "2023-12-02T05:47:51Z")

</div>

Now please post the file at:

> [@Alex-King-1998](#):
>
> `"D:\DjangoTutorial1Attempt2\mysite\polls\views.py"`

If this file does not have this line at line 94:

> [@Alex-King-1998](#):
>
> `class QuestionIndexViewTests(TestCase):`

Then you’ve got something seriously messed up here, and I have no idea how we can possibly help you fix it.

---

<div class="post-metadata">

**Author:** ![Alex-King-1998](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alex-king-1998/32/17235_2.png) [@Alex-King-1998](https://forum.djangoproject.com/u/Alex-King-1998)\
**Post date:** [December 2, 2023, 6:08am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/16 "2023-12-02T06:08:07Z")

</div>

Here is the file you requested:

```auto
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.template import loader
from django.views import generic
from django.utils import timezone

from .models import Choice, Question

class IndexView(generic.ListView):
    template_name = "polls/index.html"
    context_object_name = "latest_question_list"

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by("-pub_date")[:5]
    
class DetailView(generic.DetailView):
    model = Question
    template_name = "polls/detail.html"

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    model = Question
    template_name = "polls/results.html"

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    context = {"latest_question_list": latest_question_list}
    return render(request, "polls/index.html", context)

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    template = loader.get_template("polls/index.html")
    context = {
        "latest_question_list": latest_question_list,
    }
    return HttpResponse(template.render(context, request))

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    output = ", ".join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/detail.html", {"question": question})

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/results.html", {"question": question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST["choice"])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(
            request,
            "polls/detail.html",
            {
                "question": question,
                "error_message": "You didn't select a choice.",
            },
        )
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, "polls/detail.html", {"question": question})

def create_question(question_text, days):
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)

```

That’s exactly why I’m confused. Why am I getting an error on an empty line?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 2, 2023, 6:35am UTC](https://forum.djangoproject.com/t/nameerror-name-testcase-is-not-defined/25635/17 "2023-12-02T06:35:30Z")

</div>

There aren’t even 94 lines in this file. What does a directory listing of the file show as the size? (When I copy what you posted, I’m seeing 3474 characters.)

I’d try deleting the file and recreating it. Close your powershell window and open a new one. Reboot. Something, anything to try and get Windows to provide information that makes sense.

I could make all sorts of conjectures as to what might be happening, but this just doesn’t make sense to me.
