Reputation: 2939
I have an html file that I generated by creating a visualization using the Bokeh library. I'd like to include it within my django site, however, I get a TemplateSyntaxError when I attempt to add it as a view. It appears that some of the syntax in the page is conflicting with Django's templating system.
How do I go about having Django serve the page without attempting to parse it as a template?
Upvotes: 6
Views: 11529
Reputation: 844
You can serve your static html file using your web server:
I personnaly use (for special cases) this to serve protected files or pictures using nginx or cherokee ,here is an exemple:
@login_required(redirect_field_name=None)
def serve_file(request,id):
'''
Where "id" is the argument that identifies
the ressource to be protected
'''
#allowed = True
# You can do your permission things here, and set allowed to True if applicable
##if allowed:
response = HttpResponse()
# construct the file's path
url=os.path.join (settings.MEDIA_ROOT,'files','page_'+id+'.html')
# test if path is ok and file exists
if os.path.isfile(url):
# let nginx determine the correct content type in this case
response['Content-Type']=""
response['X-Accel-Redirect'] = url
#response['X-Sendfile'] = url
# other webservers may accept X-Sendfile and not X-Accel-Redirect
return response
return HttpResponseForbidden()
This solution can work with any file type, Removing the @login_required removes the protection ;)
!! Be carfull to ensure the type check of 'id' variable by regex in urls.py
Upvotes: 2
Reputation: 5289
You can use the verbatim tag in your template so that django's rendering system doesn't parse that section of your page:
{% verbatim %}
<!-- Template tags ignored in here -->
{% endverbatim %}
This way if in the future you want to use Django's template tags on that page you won't have to go back and change the view and then implement this solution anyways.
Upvotes: 6
Reputation: 2177
Based on the base template docs, you can just return an HttpResponse directly, without using any render functions:
https://docs.djangoproject.com/en/1.8/topics/http/views/
Since the HttpResponse just takes a string for the response content, you could just read the raw file in from wherever it is stored, and return it this way.
When you use render_to_response
or render
, this just loads the template, parses it, constructs the resulting string, and returns it wrapped in an HttpResponse anyway, so if you don't want to do any rendering, you can skip the template system entirely.
Upvotes: 8