Render Django Template

Render Django Template Dec. 4, 2020

Step 1: Create the HTML Page

Create a HTML in templates folder 

Step 2: Create view

  • Open views.py from your app folder.
  • Import render function if not imported yet.
  • Create a function to render the template.
    from django.shortcuts import render
    
    def index(request):
         return render(request, 'index.html')
  • The function takes a required parameter which is passed by sending HttpRequest. 
  • render function takes two required parameters
    • request
    • template name

Step 3: Update URL

  • Open urls.py from your app folder.
  • import views and path if not yet imported. 
  • Add your path inside the urlpatterns.
    from . import views
    from django.urls import path
    
    urlpatterns = [
         ...,
         path('home',views.index)
    ]

Your template is ready to render. Run the server to render your template.

You can automate all these task by running the following python code

import webbrowser
import os 

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>This is your new HTML page. Change the file content in templates folder</h1>
</body>
</html>
'''

def createHTML(project, app, path):
    root = os.getcwd()
    urls = f'''
    path('{path}',views.{path}),
]
        '''
    views = f'''\n
def {path}(request):
    return render(request,'{path}.html')
        '''
    with open(f'{root}/{project}-VE/{project}/{app}/views.py', 'a+', encoding='utf-8') as f:
            f.write(views)
    os.system(f'call {project}-VE/Scripts/activate')
    os.chdir(os.path.join(root,f'{project}-VE/{project}/templates'))
    with open(f'{path}.html','w+',encoding='utf-8') as f:
        f.write(html)
    os.chdir(f'../{app}')
    with open('urls.py','r+',encoding='utf-8') as f:
        _ = f.read().replace(']',urls)
    with open('urls.py', 'w', encoding='utf-8') as f:
        f.write(_)
    os.chdir(os.path.join(root, f'{project}-VE/{project}'))
    webbrowser.open(f'http://127.0.0.1:8000/{path}')
    os.system('python manage.py runserver')



project = input('Project: ')
app = input('App: ')
page = input('Page: ')
createHTML(project, app, page)

If you have any doubt or you are getting any error. Write down in comment section.

Don't forget to rate.

 


Rate this post

Comments

ANWESHA PRIYA 5 months, 1 week ago
Easy go learning platform.