Ad

Render_to_string Gives Error Whereas Render Works

- 1 answer

I am trying to render a response back to an Ajaz request. The view is reached in the python code, but if I try and render the response to string using render_to_string then I get an error stating:

django.template.exceptions.TemplateDoesNotExist:

If I run the render method with the same parameters then I don't get an error. The code for each looks like:

    html = render_to_string(request, 'planner/viewconnections.html', { 'routes' : routelist })
    render(request, 'planner/viewconnections.html', { 'routes' : routelist })

Obviously the first one is what I want to run so I can obtain the raw html back to the AJAX success function.

My templates configuration in settings.py looks like:

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',
        ],
    },
},

]

I have tried adding the template directory as below, but I still get the same error.

ROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname((__file__)),".."))

   # Other settings...
   TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, "planner/templates"),
)

Can someone help? My search on this problem let me to add the TEMPLATE_DIRS in settings, but that didn't work. I don't understand why one render method can pick up the template, but the other doesn't.

Ad

Answer

in django render_to_string request paramter is not required

syntax

render_to_string(template_name, context=None, request=None, using=None)



 html = render_to_string('planner/viewconnections.html', { 'routes' : routelist })

refer this https://docs.djangoproject.com/en/2.1/topics/templates/#django.template.loader.render_to_string

Ad
source: stackoverflow.com
Ad