Home > Mobile >  How to generate a (html) file from a view in Django
How to generate a (html) file from a view in Django

Time:11-05

I have a Django-driven website with several applications which are dynamically updated, but not too often, like "About", "Our services", etc. They have a two-level structure of pages, which I want to reflect in the top pop-up menu (see the picture).

I could make it as a custom simple_tag called each time from the base.html template. It would generate a menu each time a user opens or reloads a page, but think it is very costly since the app structure is changed seldom (say, once a year).

piece of the popup menu

Instead, I want to like to generate an HTML code of the menu each time the app structure is updated. It will be stored as a statical HTML file, so my base.html will include the menu as a ready piece of code.

Are there recipes on how to generate an HTML file from the views (CreateView, UpdateView, DeleteView)?

CodePudding user response:

You can use the render_to_string function from django that generated the html result from a template:

from django.template import loader

content = loader.render_to_string(template_name, context)

content contains the html result of rendering. You can add request object in the render_to_string function if needed.

you can find documentation about function here: https://docs.djangoproject.com/en/4.1/topics/templates/#django.template.loader.render_to_string

  • Related