Traceback Error in Django Test Client

In “Writing Your First Django App, Part 5”, in the section “Django Test Client” I am getting the following Traceback Error when entering the command response = client.get(reverse("polls:index") in the shell:

Internal Server Error: /polls/
Traceback (most recent call last):
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 220, in _get_response
    response = response.render()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 114, in render
    self.content = self.rendered_content
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 90, in rendered_content
    template = self.resolve_template(self.template_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 72, in resolve_template
    return select_template(template, using=self.using)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py", line 47, in select_template
    raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: polls/index.html, polls/question_list.html
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 927, in get
    response = super().get(path, data=data, secure=secure, headers=headers, **extra)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 457, in get
    return self.generic(
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 609, in generic
    return self.request(**r)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 891, in request
    self.check_exception(response)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 738, in check_exception
    raise exc_value
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 220, in _get_response
    response = response.render()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 114, in render
    self.content = self.rendered_content
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 90, in rendered_content
    template = self.resolve_template(self.template_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 72, in resolve_template
    return select_template(template, using=self.using)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py", line 47, in select_template
    raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: polls/index.html, polls/question_list.html

When I enter response.status_code after this, it still returns 404 and not the expected 200

Here is my models.py:

import datetime

from django.db import models
from django.utils import timezone

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
    def test_was_published_recently_with_old_question(self):
        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):
        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)
    

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

This indicates one of a couple of different issues -

  • Your TEMPLATES section in your settings isn’t correct.
  • Those referenced template files don’t exist
  • Those files aren’t in the right directory

If you’d like more specific assistance with this, please post the contents of your settings.py file, along with identifying the full directory path where your project resides and where the template files are located relative to that. (Also make sure you don’t have a duplicate definition for the TEMPLATES settings.)

Here is my Settings.py file:

"""
Django settings for mysite project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-fd(@wl!=&fa^hga-sr8nmnz3cgu#^a04+k(j6xj^3!@p@1(#z9'

# 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.2/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/4.2/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.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UCT'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Project resides in the following directory: “D:\DjangoTutorial1Attempt2\mysite”, with template files located in “D:\DjangoTutorial1Attempt2\mysite\polls\templates”

This directory identifies the “base” directory for template references.

If your render function is specifying polls/index.html, then the template should reside in “D:\DjangoTutorial1Attempt2\mysite\polls\templates\polls\index.html”

That was it. The index.html was residing in “D:\DjangoTutorial1Attempt2\mysite\polls\templates\index.html” , when it should have been located in “D:\DjangoTutorial1Attempt2\mysite\polls\templates\polls\index.html”

Thank you for the help.

For me it is already in the Templates/polls directory it still is showing this error

Welcome @PravasMohanty !

This thread has been marked as solved, and so your post is not likely to attract attention. If you’re having an issue that you would like assistance with, I suggest you open a new topic with all the details of that issue. Include the full traceback and the code that you think is causing the problem.

Side note: When posting code, templates, or tracebacks here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted.

this is my eclat algorithm view.py code. I want to choose csv file and analyze with django but ı have this problem. can you help me ?

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8080/eclat/

Django Version: 5.0
Python Version: 3.12.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'myapp']
Installed 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']



Traceback (most recent call last):
  File "C:\Users\emret\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\emret\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\deprecation.py", line 136, in __call__
    response = self.process_response(request, response)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\emret\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response
    if response.get("X-Frame-Options") is not None:
       ^^^^^^^^^^^^

Exception Type: AttributeError at /eclat/
Exception Value: 'Eclat' object has no attribute 'get'
class Eclat:
    def __init__(self, min_support):
        self.min_support = min_support
        self.itemsets = {}  # Sık öğe kümelerini saklamak için sözlük

    def fit(self, transactions):
        # Transaction'ları geçerek sık öğe kümelerini bulma işlemi
        self._find_frequent_itemsets(transactions)
    
    def _find_frequent_itemsets(self, transactions, itemset=None, prefix=None):
        if itemset is None:
            itemset = set()
        if prefix is None:
            prefix = set()

        # Tüm tek öğelerin sayısını hesapla
        item_count = {}
        for transaction in transactions:
            for item in transaction:
                if item in item_count:
                    item_count[item] += 1
                else:
                    item_count[item] = 1

        # Min_support'tan büyük olan öğeleri sık öğe kümeleri listesine ekle
        for item, count in item_count.items():
            support = count / len(transactions)
            if support >= self.min_support:
                self.itemsets[frozenset([item])] = support

        # Prefix ile birleştirerek yeni öğe kümeleri oluştur
        for item in itemset:
            new_itemset = prefix | {item}
            new_transactions = [transaction for transaction in transactions if new_itemset.issubset(transaction)]
            support = len(new_transactions) / len(transactions)
            if support >= self.min_support:
                self.itemsets[frozenset(new_itemset)] = support
                self._find_frequent_itemsets(new_transactions, itemset - {item}, new_itemset)

    def get_frequent_itemsets(self):
        return self.itemsets

# CSV dosyasından veri okuma
def read_csv(file_path):
    data = pd.read_csv(file_path)
    transactions = []
    for index, row in data.iterrows():
        transaction = set(row.dropna())  # None değerlerden kurtul
        transactions.append(transaction)
    return transactions

def show_frequent_itemsets(request):
    # Örnek CSV dosyası yolu
    file_path = "retail_dataset.csv"

    # CSV dosyasından veri okuma
    transactions = read_csv(file_path)

    # Eclat algoritmasını kullanarak sık öğe kümelerini bulma
    min_support = 0.4
    eclat = Eclat(min_support)
    eclat.fit(transactions)
    frequent_itemsets = eclat.get_frequent_itemsets()

    # Sık öğe kümelerini çubuk grafik olarak görselleştirme
    itemsets = [str(itemset) for itemset in frequent_itemsets.keys()]
    supports = [support for support in frequent_itemsets.values()]

 # Grafik verilerini HTML sayfasına aktar
    context = {
        'itemsets': itemsets,
        'supports': supports,
    }

    plt.figure(figsize=(14, 8))

    # Çubuk grafik
    plt.subplot(2, 2, 1)
    plt.barh(itemsets, supports, color='skyblue')
    plt.xlabel('Support')
    plt.ylabel('Itemsets')
    plt.title('Frequent Itemsets')
    plt.gca().invert_yaxis()  # Y ekseni tersine çevirme

    # Histogram
    plt.subplot(2, 2, 2)
    plt.hist(supports, bins=10, color='lightgreen')
    plt.xlabel('Support')
    plt.ylabel('Frequency')
    plt.title('Support Distribution')

    # Scatter plot
    itemset_sizes = [len(itemset) for itemset in frequent_itemsets.keys()]
    plt.subplot(2, 2, 3)
    plt.scatter(itemset_sizes, supports, color='salmon')
    plt.xlabel('Itemset Size')
    plt.ylabel('Support')
    plt.title('Support vs Itemset Size')

    plt.tight_layout()  # Grafiklerin örtüşmesini önlemek için

    # Matplotlib figürünü HTML'e gömme
    buffer = io.BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    image_png = buffer.getvalue()
    buffer.close()

    # HTML'e gömmek için base64 formatına dönüştür
    graphic = base64.b64encode(image_png)
    graphic = graphic.decode('utf-8')

    plt.close()  # Grafiği kapat

    return render(request, 'eclat.html', context)
       

and my eclat.html page

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />

    <title>OnePage Bootstrap Template - Index</title>
    <meta content="" name="description" />
    <meta content="" name="keywords" />
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/papaparse@5.3.0/papaparse.min.js"></script>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@4.0.0/dist/embed-amd.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/requirejs@2.3.6/require.min.js"></script>
    <!-- Favicons -->
    <link href="{% static 'assets/img/favicon.png' %}" rel="icon" />
    <link
      href="{% static 'assets/img/apple-touch-icon.png' %}"
      rel="apple-touch-icon"
    />

    <!-- Google Fonts -->
    <link
      href="{% static 'https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i' %}"
      rel="stylesheet"
    />

    <!-- Vendor css Files -->
    <link href="{% static 'assets/vendor/aos/aos.css' %}" rel="stylesheet" />
    <link
      href="{% static 'assets/vendor/bootstrap/css/bootstrap.min.css' %}"
      rel="stylesheet"
    />
    <link
      href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"
      rel="stylesheet"
    />
    <link
      href="{% static 'assets/vendor/boxicons/css/boxicons.min.css' %}"
      rel="stylesheet"
    />
    <link
      href="{% static 'assets/vendor/glightbox/css/glightbox.min.css' %}"
      rel="stylesheet"
    />
    <link
      href="{% static 'assets/vendor/remixicon/remixicon.css' %}"
      rel="stylesheet"
    />
    <link
      href="{% static 'assets/vendor/swiper/swiper-bundle.min.css' %}"
      rel="stylesheet"
    />

    <!-- Template Main css File -->
    <link href="{% static 'assets/css/style.css' %}" rel="stylesheet" />
    <style>
      table {
        border-collapse: collapse;
        width: 100%;
        margin-top: 20px;
      }

      th,
      td {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
      }

      th {
        background-color: #f2f2f2;
      }
    </style>
  </head>

  <body>
    <!-- ======= Header ======= -->
    <header id="header" class="fixed-top">
      <div class="container d-flex align-items-center justify-content-between">
        <h1 class="logo"><a href="index.html">Lion Dreamin</a></h1>
        <!-- Uncomment below if you prefer to use an image logo -->
        <!-- <a href="index.html" class="logo"><img src="{% static 'assets/img/logo.png' %}" alt="" class="img-fluid"></a>-->

        <nav id="navbar" class="navbar">
          <ul>
            <li>
              <a class="nav-link scrollto active" href="{% url 'myapp:index' %}"
                >Home</a
              >
            </li>
            <li>
              <a class="nav-link scrollto" href="{% url 'myapp:index' %}#about"
                >About</a
              >
            </li>
            <li>
              <a
                class="nav-link scrollto"
                href="{% url 'myapp:apriori' %}"
                >Apriori</a
              >
            </li>
             <li><a class="nav-link scrollto" href="{% url 'myapp:eclat' %}">Eclat</a></li> 
            <li><a class="nav-link scrollto" href="#services">Services</a></li>
            <li>
              <a class="nav-link scrollto o" href="#portfolio">Portfolio</a>
            </li>
            <li><a class="nav-link scrollto" href="#team">Team</a></li>
            <li><a class="nav-link scrollto" href="#pricing">Pricing</a></li>
            <li class="dropdown">
              <a href="#"
                ><span>Drop Down</span> <i class="bi bi-chevron-down"></i
              ></a>
              <ul>
                <li><a href="#">Drop Down 1</a></li>
                <li class="dropdown">
                  <a href="#"
                    ><span>Deep Drop Down</span>
                    <i class="bi bi-chevron-right"></i
                  ></a>
                  <ul>
                    <li><a href="#">Deep Drop Down 1</a></li>
                    <li><a href="#">Deep Drop Down 2</a></li>
                    <li><a href="#">Deep Drop Down 3</a></li>
                    <li><a href="#">Deep Drop Down 4</a></li>
                    <li><a href="#">Deep Drop Down 5</a></li>
                  </ul>
                </li>
                <li><a href="#">Drop Down 2</a></li>
                <li><a href="#">Drop Down 3</a></li>
                <li><a href="#">Drop Down 4</a></li>
              </ul>
            </li>
            <li><a class="nav-link scrollto" href="#contact">Contact</a></li>
            <li>
              <a class="getstarted scrollto" href="#about">Get Started</a>
            </li>
          </ul>
          <i class="bi bi-list mobile-nav-toggle"></i>
        </nav>
        <!-- .navbar -->
      </div>
    </header>

    <main id="main">
      <section id="pricing" class="pricing">
        <div class="container" data-aos="fade-up">
          <div class="row">
            <h1>Frequent Itemsets</h1>
    
            <!-- CSV dosyasını seçmek için bir form -->
            <form id="csv-form" enctype="multipart/form-data">
                <input type="file" id="csv-file" name="csv-file">
                <input type="submit" value="Analyze">
            </form>
        
            <div id="charts"></div>
        
            <script>
                // Form gönderildiğinde
                $('#csv-form').submit(function(event) {
                    event.preventDefault(); // Sayfa yenilemesini engelle
                    var formData = new FormData($(this)[0]); // Form verilerini al
        
                    // CSV dosyasını sunucuya gönder
                    $.ajax({
                        url: 'analyze_csv/', // Sunucu tarafındaki URL
                        type: 'POST',
                        data: formData,
                        async: false,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function(data) {
                            // Grafikleri görüntülemek için Matplotlib'in HTML çıktısını al
                            var chartsDiv = document.getElementById('charts');
                            var chartsHtml = $(data).find('#charts').html();
                            chartsDiv.innerHTML = chartsHtml;
                        }
                    });
                    return false;
                });
            </script>
        
            <style>
                #graphs-container {
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-between;
                }
        
                .graph {
                    width: calc(50% - 10px);
                    margin-bottom: 20px;
                }
        
                @media screen and (min-width: 1200px) {
                    .graph {
                        width: calc(33.33% - 10px);
                    }
                }
        
                @media screen and (max-width: 768px) {
                    .graph {
                        width: calc(100% - 20px);
                    }
                }
            </style>

    <!-- End Footer -->

    <div id="preloader"></div>
    <a
      href="#"
      class="back-to-top d-flex align-items-center justify-content-center"
      ><i class="bi bi-arrow-up-short"></i
    ></a>

    <!-- Vendor js Files -->
    <script src="{% static 'assets/vendor/purecounter/purecounter_vanilla.js' %}"></script>
    <script src="{% static 'assets/vendor/aos/aos.js' %}"></script>
    <script src="{% static 'assets/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
    <script src="{% static 'assets/vendor/glightbox/js/glightbox.min.js' %}"></script>
    <script src="{% static 'assets/vendor/isotope-layout/isotope.pkgd.min.js' %}"></script>
    <script src="{% static 'assets/vendor/swiper/swiper-bundle.min.js' %}"></script>
    <script src="{% static 'assets/vendor/php-email-form/validate.js' %}"></script>

    <!-- Template Main js File -->
    <script src="{% static 'assets/js/main.js' %}"></script>
  </body>
</html>

Welcome @tasemre !

This thread has been marked as solved, and so your post is not likely to attract attention.

I suggest you open a new topic for this issue and post these details in that topic.