简体   繁体   中英

Django returning static HTML in views.py?

So I have a standard Django project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using HttpResponse() I know it's a bit unorthodox , but this is an example of what I'm thinking about:

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response

def index(request):
    html = """
<html>
  <body>
    This is my bare-bones html page.
  </body>
</html>
"""
    return HttpResponse(html)

My corresponding JS and stylesheets would be stored in the same directory as views. py in my app in this example. Just making sure: I'm not asking if this works, because I already know the answer is yes, I just want to know if there are any disadvantages/drawbacks to this method, and why don't more people do this?

大多数人不使用它,因为它将Python与HTML混合在一起,变得非常混乱,并且很快无法使用

您可以使用内置的模板渲染器来获取作品过滤器/ templatetags / etc

To answer your question, this solution works alright, but it is not adopted by many programmers because it makes the whole code disorganized and not easy to understand. Also, this system would not be good for large projects because the code would contain lots of html in the same file as the python. It is always nice and time saving to separate code into files based on performance.

A better solution

Save your html in a folder called templates in the current directory, in this case, the templates folder can contain an index.html file which would have

<html>
  <body>
    This is my bare-bones html page.
  </body>
</html>

in the views create an index view for this template using the code below

def index(request):
    return render(request, 'index.html')

if you would need to pass in some data to the html you can use context in the request as shown below:

def index(request):
    context = {
         "name":"some name"
    }
    return render(request, 'index.html', context=context)

access the data in html using the structure below:

<html>
  <body>
    The data passed to the page is {{name}}.
  </body>
</html>

I hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM