How to make VSCode format Django templates properly?
Asked Answered
S

11

50

I love VSCode on-save auto-format, until it messed up with my template code.

It wrongly formats my django template syntax into one line code (sometimes really long line). So instead of having this code

{% for row in 'ABCDEFGH' %}
<tr>
  {% for col in '123456789012345' %}
    <td>
      {% with forloop.counter|stringformat:"s" as counter %}
        {% with row|add:counter as seat_num %}
          {% if seat_num not in oc_seats %}
            <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats">
          {% endif %}
          <br> {{ seat_num }} 
        {% endwith %}
      {% endwith %}
     </td>    
   {% endfor %}
</tr>
{% endfor %}

I end up have this code

{% for row in 'ABCDEFGH' %}
<tr>
  {% for col in '123456789012345' %}
  <td style="text-align: center; border: 1px solid #aaa;">
    {% with forloop.counter|stringformat:"s" as counter %} {% with row|add:counter as seat_num %} {% if seat_num not in oc_seats %}
    <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats"> {% endif %} {{ seat_num }} {% endwith %} {% endwith %}
  </td>
  {% endfor %}
</tr>
{% endfor %}

I tried to disable format on save by changing user settings into {"editor.formatOnSave": false} but still haven't gotten any luck.

Is there any configuration that I can use to make it work better?

PS: I'm using VSCode version 1.9 on Sierra MacOSx

Sensualist answered 10/2, 2017 at 23:55 Comment(1)
Does this answer your question? There is no document formatter for 'django-html'-files installedFlapjack
P
4

you can disable the default html formatter, goto File > Preferences > User or Workspace Settings, in HTML settings you will find :

// Enable/disable default HTML formatter (requires restart)
  "html.format.enable": true,

I think VSCode uses js-beautify as default formatter, you can use beautify extension to override it settings with .jsbeautifyrc in project directory

Po answered 3/3, 2017 at 12:56 Comment(0)
C
29

I used the beautify extension instead which worked right away while prettier was still putting on one line. Credit goes to kimanihuon on this stackoverflow page.

  1. Add the following to settings.json
"files.associations": {
   "**/*.html": "html",
   "**/templates/*/*.html": "django-html",
   "**/templates/*": "django-txt",
   "**/requirements{/**,*}.{txt,in}": "pip-requirements"
},

"emmet.includeLanguages": {
   "django-html": "html"
},
  1. Install beautify and then add following to settings.json
"beautify.language": {
   "html": [
       "htm",
       "html",
       "django-html"
   ]
},
  1. Restart VSCode just in case
Cholecystectomy answered 6/9, 2020 at 19:14 Comment(3)
beautify completes the trick!Kwapong
Beautify no longer existsAssyrian
Try djlint, see one of the answers belowRhenium
T
23

Alexa has a good point in her answer. The file mode needs to be changed in "Django/HTML" to prevent VS CODE for formatting it.

How to change the file mode?

A quick solution is to use this extension called vscode-Django and adjust your setting like this as said in his documentation.

"files.associations": {
    "**/templates/*.html": "django-html",
    "**/templates/*": "django-txt"
}

With those setting any file located in the template folder will be considered as a Django template file and will not be affected by HTML autoformat.

PS: The extension is still in preview mode, hope it will get better with time.

Torey answered 13/6, 2019 at 16:19 Comment(0)
C
17

Changing the language mode of the file to "Django/HTML" will also prevent VSCode from autoformatting it.

Coalfish answered 23/1, 2019 at 16:8 Comment(6)
How to change the language mode of a file?Torey
In the footer at the bottom right of VSCode application you can click on the current detected language and change itCoalfish
Do I need to install a specific extension to see this language mode? I do not have it.Silverware
The button itself does not say 'language mode', but rather the currently detected language, like 'HTML'Coalfish
No extension needed!Coalfish
You've got to install the Django extensionMarrakech
B
8

I tried and now highly recommend the djlint extension to format Django HTML code. It is effective and quite configurable.

First, you need to manually install the Python package djlint in your current virtual environment (or globally).

Then you need to select Python interpreter where you installed the djlint extension in VSCode - Open the Command Palette, type Python: Select Interpreter, then select the Python environment where you installed djlint

Finally, install the actual djlint-vscode VSCode extension.

With your code, the output is:

{% for row in 'ABCDEFGH' %}
    <tr>
        {% for col in '123456789012345' %}
            <td style="text-align: center; border: 1px solid #aaa;">
                {% with forloop.counter|stringformat:"s" as counter %}
                    {% with row|add:counter as seat_num %}
                        {% if seat_num not in oc_seats %}
                            <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats">
                        {% endif %}
                        {{ seat_num }}
                    {% endwith %}
                {% endwith %}
            </td>
        {% endfor %}
    </tr>
{% endfor %}
Beguin answered 12/5, 2022 at 12:40 Comment(2)
Since beautify is dead this is the best option I believe.Jemmie
You probably want to combine this extension with the Django extension by Baptiste Darthenay, which will add support for the Django HTML file types and other things.Subarctic
T
7

Prettier in VSCode was the culprit in my situation. I got it to stop formatting with following in my settings.json.

"files.associations": {
   "**/*.html": "html",
   "**/templates/*/*.html": "django-html",
   "**/templates/*": "django-txt",
   "**/requirements{/**,*}.{txt,in}": "pip-requirements"
},    
"[django-html]": {
   "editor.defaultFormatter": "batisteo.vscode-django"
},

files.associations sets the language mode for the templates to django-html. [django-html] sets the settings for that language mode. As of writing this, the formatter in batisteo.vscode-django doesn't do anything for me (so it's the same as null in its place), but I left it there in case the django extension ever does.

Tapis answered 18/5, 2021 at 19:29 Comment(0)
P
4

you can disable the default html formatter, goto File > Preferences > User or Workspace Settings, in HTML settings you will find :

// Enable/disable default HTML formatter (requires restart)
  "html.format.enable": true,

I think VSCode uses js-beautify as default formatter, you can use beautify extension to override it settings with .jsbeautifyrc in project directory

Po answered 3/3, 2017 at 12:56 Comment(0)
P
3

Had the same issue, found a post where the person disabled JS-CSS-HTML Formatter extension (https://mcmap.net/q/355629/-visual-studio-code-formats-on-save-no-matter-what-i-do-how-do-i-stop-this) and it fixed the issue. Tested on mine and it seems to have worked too. Hope that helps

Pronounce answered 25/2, 2017 at 23:37 Comment(1)
Funny thing is I don't even have that extension, but the problem still exists.Sensualist
S
2

You can disable the formatting option for some of the languages:

Go to Extensions and then "Extension settings" of Prettier and add django-html for this case as below.

disable language - prettier

Sculley answered 13/12, 2020 at 9:7 Comment(0)
K
1

vscode eslint does not work on Django files. so to disable the prettier extension just add this to your settings.json

"[django-html]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },

A similar solution would be

"[django-html]": {
    "editor.formatOnSave": false
  },

worked for me.

Kimberleykimberli answered 1/2, 2023 at 21:47 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Manassas
B
-1

in VSCode's settings.json, add the following : emmet.includeLanguages": {"django-html": "html"}

Bunche answered 12/6, 2020 at 11:17 Comment(2)
what will this do?Frigging
Could you explain why this is a solution, instead of just saying what to do?Eppie
S
-1

For Prettier users, I want autoformat to work, thus:

Press ctrl/cmd+shift+p to open command bar and enter settings, then choose "Open User Settings (JSON)".

Append following to settings.json file:

  "[django-html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnType": true,
    "editor.formatOnSave": true,
    "editor.formatOnSaveMode": "file"
  }

This will not break any snippets defined for django html.

Still very convenient that all html snippets ant autocomplete also works in django templates, thus add

  "emmet.includeLanguages": { "django-html": "html" },

and you can choose any formatter like:

  • esbenp.prettier-vscode - does autoformat
  • dbaeumer.vscode-eslint - does not for me
  • batisteo.vscode-django - does not for me
Steiermark answered 11/5, 2024 at 9:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.