Django generating strange code

5

I'm using visual studio community and I created a web project with Django, but when I make the homepage, it's generating this code:

AndthecodeIhaveisthis:

{%loadstaticfiles%}<!DOCTYPEhtml><html><head><metacharset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{ title }}</title>

        <link rel="stylesheet" type="text/css" href="{% static 'app/content/materialize.css' %}" />
        <link rel="stylesheet" type="text/css" href="{% static 'app/content/app.css' %}" />
        <link rel="stylesheet" type="text/css"  href="https://fonts.googleapis.com/icon?family=Material+Icons" />
    </head>
    <body>

Does anyone know why running it does it? esculhamba or html?

This is creating a space on my page that should not have.

code that renders:

def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/index.html',
        {
            'title':'Home Page',
            'year':datetime.now().year,
        }
    )
    
asked by anonymous 06.05.2016 / 04:07

1 answer

2

The code &#65279; corresponds to the Unicode character U+FEFF , much used in UTF-16 encodings as "byte order mark" (BOM). However, some text editors (such as Windows Notepad) put this same BOM into UTF-8 files, which do not need BOM (since the byte order is always the same). This is probably done with the intention of "tagging" the file as UTF-8, although this practice is discouraged.

Because your modified file had this character at the beginning of the file, it was sent to the browser along with the rest, and the parsing rules of the browser determined that it should be part of the content of the file. Because of the robustness / fault tolerance of the usual HTML parsing algorithms, not having html and body does not prevent them from accepting content - putting them to you. So, the resulting DOM ended with an empty% wrap and everything in your template within the% wrapper created automatically.

The ideal way to fix this is by removing BOM from your files. Alternatively, maybe it is possible to cause the browser itself to ignore this BOM, informing it in head that the file is encoded as "UTF-8 with BOM" body ):

resposta = render(
    request,
    'app/index.html',
    {
        'title':'Home Page',
        'year':datetime.now().year,
    }
)
resposta.charset = "UTF-8Y"
return resposta

(I can not test at this time if the above solution will be accepted by major browsers, so I suggest using them only as a last resort)

Sources: These three questions in SOen.

    
07.05.2016 / 22:25