New to Django - Template Does not exist

Hi! I am trying to create a webapp in Django and just started learning today. I am confused as to why my path isn’t correctly set-up. If more information is needed, let me know!

Any help and explaination would be awesome thank you!

syllink/urls.py

from django.conf import settings
from django.conf.urls.static import static
from . import views
from django.urls import path

app_name = "syllink"
urlpatterns = [
    path("", views.IndexView.as_view(), name="index"),
    path('upload/', views.upload_file, name='upload'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

from django.shortcuts import render
from django.views import generic
from django.core.files.storage import FileSystemStorage
from .models import Syllabus_Uploader


class IndexView(generic.ListView):
    template_name = "syllink/index.html"

    def get_queryset(self):
        """Return the last five published questions."""
        return None

def upload_file(request):
    if request.method == 'POST':
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()

        # Generate a unique filename to avoid conflicts
        from django.utils.text import unique_slugify
        filename = unique_slugify(myfile.name)
        filename = f"{filename}.{myfile.name.split('.')[-1]}"  # Preserve extension

        uploaded_file = fs.save(filename, myfile)
        uploaded_file_url = fs.url(uploaded_file)

        # Save the uploaded file to the model instance
        new_syllabus = Syllabus_Uploader(syllabus=uploaded_file)
        new_syllabus.save()

        return render(request, 'upload_file.html', {'uploaded_file_url': uploaded_file_url})
    else:
        return render(request, 'upload_file.html')

upload_file.html

{% extends 'base.html' %}

{% load static %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile">
    <button type="submit">Upload</button>
  </form>

  <p><a href="{% url 'index' %}">Return to home</a></p>
{% endblock %}

index.html

{% load static %}

<!-- <link rel="stylesheet" href="{% static 'polls/style.css' %}"> -->
<ul>
    <!-- url 'namespace:name of path'-->
    <li><a href="{% url 'syllink:upload' %}">Click here to upload a file</a></li>
</ul>

models.py

from django.db import models

# Create your models here.
class Syllabus_Uploader(models.Model):
    syllabus = models.FileField(upload_to='syllabi/')

Please be more specific, post the complete error you are receiving, along with the traceback.

Also show your directory structure and where these files are located.

Finally, post the TEMPLATES setting from your settings.py file.

1 Like

Error + Traceback:

Internal Server Error: /syllink/upload/
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/phil/vscode/SylLink_App/syllink/views.py", line 33, in upload_file
    return render(request, 'upload_file.html')
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/shortcuts.py", line 25, in render
    content = loader.render_to_string(template_name, context, request, using=using)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/template/loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/template/loader.py", line 19, in get_template
    raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: upload_file.html

Templates:

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "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",
            ],
        },
    },
]

Hello!

Here, instead of just upload_file.html, try using syllink/upload_file.html. Since, relative to the templates folder, that is where your file exists, you have to point it exactly there.

Hope this helps!

1 Like