0

I want to dynamically generate a page using the base template

I need to insert a piece of HTML code on the page

I have checkboxes and after selecting some, generate new ones according to favorites.

It doesn't work as it should :

def index(request):
    context = {'content': '<h1>hello</h1>'}
    return render(request, 'base.html', context)

on the HTML page :

<h1>hello</h1>

how to insert html tags into base template?

4
  • before you return as HttpResponse you need to render the content in order to convert django tags into html Commented Dec 20, 2021 at 8:51
  • its not possible what you're doing. Commented Dec 20, 2021 at 8:52
  • @Razenstein how can i do that? Commented Dec 20, 2021 at 9:44
  • see the answers below Commented Dec 20, 2021 at 9:46

2 Answers 2

1

you can use render:

views.py

from django.shortcuts import render

def index(request):
context = {'foo': 'bar'}
    return render(request,'yourapp_name/your_html.html',context)

your_html.html

{% extends 'yourapp_name/base.html' %} 

{% block content %}

Hello

{% endblock %}

remember your html files should have this path: yourapp_name/templates/yourapp_name/your_html.html

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

4 Comments

I can't insert the generated content
@VG would you please be more specific ?
I have checkboxes and after selecting some, generate new ones according to favorites. Displaying the whole page in a string is awful, I'm looking for an easier option
If I may suggest: please follow one of the django basic tutorials in order to get familiar with the philosophy and frist steps. It seems you are new to html, javascript etc. also.
0

the tags you want to use are django specific tags that neet to be converted by the django renderer. Put the html in a template file and render it as response:

def index(request):

   ....

 return render(request, "path/your_template.html", context)

please follow the django docs to understand where to place the templates so that django will find them.

2 Comments

I caught Exception Type: TypeError Exception Value: context must be a dict rather than set.
` def index(request): context= {'content': '<h1>hello</h1>'} return render(request, 'base.html', context) ` and have <h1>hello</h1>... have any ideas how to transfer HTML?

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.