0

I am new to Django and I have the following problem

With views.py I render a page called 'results_links.html' located in application templates directory which has an 'include' statement toward another page 'MAPE_history.csv.html' located in 'upload' directory (which is also defined in settings.py as template directory). I want to dynamically pass the file to be used in 'included' statement from views.py. For the test I use same file: MAPE_history.csv.html The problem I have is that I receive a 'template not existing'error from include statement. If I remove the statement of I replace the 'content' variable with the file name, I do not receive a problem. Here is the code:

    ### views.py
from django.shortcuts import render
from django.http import HttpResponse
import os
from formupload import Best_model_forecast_v11

# Create your views here.
def home(request):
    return render(request, 'index.html', {'what':'Django File Upload'})

def upload(request):
    if request.method == 'POST':
        handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
        MAPE_file = 'MAPE_'+str(request.FILES['file'])+'.html'
        return render(request,'result_links.html',{'content':MAPE_file})
    elif request.method == 'GET':
        return render(request,'result_links.html',{'content':'MAPE_history.csv.html'})
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'upload/MAPE_history.csv; filename="MAPE_history.csv"'
        return response
    return HttpResponse("Failed")

def handle_uploaded_file(file, filename):

    if not os.path.exists('upload/'):
        os.mkdir('upload/')
    if not os.path.exists('forecast/'):
        os.mkdir('forecast/')
    with open('upload/' + filename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    #print(Best_model_forecast_v11.main('upload/' + filename))
    return Best_model_forecast_v11.main('upload/' + filename)

### result_links.html
<html>
<head>
  <title>Rezultate</title>
<IMG SRC="logo.jpg" ALT="" WIDTH=100 HEIGHT=100>
</head>
<a href="D:/FLORIAN/Django/mysite/upload/MAPE_history.csv.html">forecast</a>

{% block content %}
    {% include 'logo.html' %}
    {% include '{content}' %} # 'template not existing' error is coming from this statement!


  <table>
    <tr>
      <td>
        <form action="{{ request.build_absolute_uri }}" method="GET" enctype="multipart/form-data">
          <input type="file" name="{content}"/>
          <br />
          <input type="submit" value="Rezultate" />
        </form>
      </td>
    </tr>
  </table>
<a href='{{ MEDIA_URL }}{{ content.relative_path }}'>{{content}}</a>
{% endblock %}

</html>

### settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates','d:/florian/django/mysite/upload/'),
            'd:/florian/django/mysite/upload/'
            ],
        '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',
            ],
        },
    },
]
### error
TemplateDoesNotExist at /upload/
{content}
Request Method: POST
Request URL:    http://localhost:8000/upload/
Django Version: 1.11.7
Exception Type: TemplateDoesNotExist
Exception Value:    
{content}
Exception Location: C:\Users\lored\Envs\simpleform\lib\site-packages\django\template\engine.py in find_template, line 148
Python Executable:  C:\Users\lored\Envs\simpleform\Scripts\python.exe
Python Version: 3.5.0
Python Path:    
['D:\\FLORIAN\\Django\\mysite',
 'C:\\Users\\lored\\Envs\\simpleform\\Scripts\\python35.zip',
 'C:\\Users\\lored\\Envs\\simpleform\\DLLs',
 'C:\\Users\\lored\\Envs\\simpleform\\lib',
 'C:\\Users\\lored\\Envs\\simpleform\\Scripts',
 'c:\\python35\\Lib',
 'c:\\python35\\DLLs',
 'C:\\Users\\lored\\Envs\\simpleform',
 'C:\\Users\\lored\\Envs\\simpleform\\lib\\site-packages']
Server time:    Tue, 28 Nov 2017 18:27:27 +0000
Template-loader postmortem

Django tried loading these templates, in this order:

Using engine django:
django.template.loaders.filesystem.Loader: d:\florian\django\mysite\upload\{content} (Source does not exist)
django.template.loaders.filesystem.Loader: d:\florian\django\mysite\upload\{content} (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\lored\Envs\simpleform\lib\site-packages\django\contrib\admin\templates\{content} (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\lored\Envs\simpleform\lib\site-packages\django\contrib\auth\templates\{content} (Source does not exist)
django.template.loaders.app_directories.Loader: D:\FLORIAN\Django\mysite\formupload\templates\{content} (Source does not exist)

templates directory

enter image description here

1
  • is this not covered in the django project tutorial? Commented Nov 28, 2017 at 19:06

3 Answers 3

1

The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes. Try using {% include content %}

Sign up to request clarification or add additional context in comments.

Comments

0

Accessing variables in Django like this requires double braces; change your {content} line to {{ content }}.

As an aside, check your "elif request.method == 'GET':" code, as the second return will never be reached.

1 Comment

I tried with all variants, double braces included. What is very strange: in the link statement {{content}} is working but not in the included statement... <a href="{{content}}">forecast</a> TemplateDoesNotExist at /upload/ {{content}} Request Method: POST Request URL: localhost:8000/upload Django Version: 1.11.7 Exception Type: TemplateDoesNotExist Exception Value: {{content}}
0

Why are you using if elif try this one

def upload(request):
    if request.method == 'POST':
        handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
        MAPE_file = 'MAPE_'+str(request.FILES['file'])+'.html'
        return render(request,'result_links.html',{'content':MAPE_file})
  
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'upload/MAPE_history.csv; filename="MAPE_history.csv"'
    return render(request,'result_links.html',{'content':'MAPE_history.csv.html'})

1 Comment

I am using elif because I do two different things: 1) when I upload the file, I run a custom py (best_model....) and I generate the 'MAPE_MAPE_history.csv.html' file which is save also in 'upload' directory. My goal now is 2) to be able to download the newly generated MAPE_history.csv.html file and I try to do this through the 'result_links.html' page where I use 'GET' method which is pointing back into 'elif'. If I can achieve my goal to simply download the resulted file, than I am willing to use any other suitable method. Thanks.

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.