Django: how to get template debug info for user in syntax mode

I have a page where users can submit their own template to a textbox as it should be that easy now. However, since this is user input, I need to verify that they are not doing anything that disrupts the rest of my application and at the same time provides helpful feedback on what they did wrong if they did something wrong.

In order to provide useful feedback, I want something similar to what django supplies me (using django 1.4):

enter image description here

The above bit in particular. I am putting the user template in the django template so I don't have to check for syntax errors and overlay myself. It looks something like this:

try:
    template = get_template_from_string(user_input)
    template.render(context=Context())
except:
    do something to ouptut the error

      

A render call is required, otherwise no exceptions will be thrown.

I've tried printing out the exception and its arguments, but this only gives very limited information. I also tried using traceback but never gave line numbers or anything in the template, only where an exception is thrown in python code. I also couldn't find anything with Google and my search through the Django source code made me wonder where the real error page is being generated ...


So basically my question is; how to get the bit of information shown in the image?

EDIT To clarify: I want users to be able to create templates so that these templates can be used when sending emails. Since Django's templating engine is already there, I decided I would use it instead of something else.

Templates themselves are safe using this snippet and some parsing of my own for variables. Everything works so far except for a helpful debug message for the user. So far, all I have is this: "Something went wrong when you parse your template, for example" unexpected block tag "), which I would like to look more like the image shown above.

+3


source to share


1 answer


I just got into the same problem. In my case, such detailed tracing is not required. So I did it like this using pure model methods



from django.core.exceptions import ValidationError
from django.core.urlresolvers import NoReverseMatch
from django.db import models
from django.template.base import Template, TemplateSyntaxError
from django.template.context import Context

class MyTemplate(models.Model):
    template = models.TextField()

    def clean(self):
        try:
            Template(self.tempalte).render(Context({}))
        except TemplateSyntaxError as tse:
            raise ValidationError('TemplateSyntaxError: %s' % tse)
        except NoReverseMatch as nrm:
            raise ValidationError('NoReverseMatch: %s' % nrm)

      

0


source







All Articles