Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Not Showing Complete Fields In a Model
I am quite new to the Django environment, Here's a problem I am facing: First I made a model: class ABC(Model): field A field B field C then, I migrated them successfully using the following commands: python manage.py makemigrations python manage.py migrate Then, I again added a new field to same model: class ABC(Model): #rest fields are here field D These also got migrated successfully. But, Here's the problem now. After migration, I am not able to see field D in the Django admin interface. (for which I want to edit the value) AM I missing anything here? (PS: Have tried sqlflush, dbshell every possible troubleshoot) I also restarted NGINX & Gunicorn (since I am hosted on AWS EC2) I am certain, that fields are getting created. Please help. -
Django Multiple-User Model
I need advice on a multiple user type. Scenario: A user can be an organization, where in this organization they can place adverts on the website. The owner of this organization(user) can edit/delete users and adverts of his own organization(group). In this organization user type there are users that also can log in and they can only see the adverts placed by them, but the owner of this group must see all adverts of his own and of his users. Think like an estate listing where an organization has multiple locations/users that can place adverts, and has to be managed by a admin user of this organization. What type or model is the best/cleanest for implementing this in a good way? Do I need the Django's User and Group model? -
Django Admin does not load CSS/JS file in Docker and setting request as cancelled
I am using Docker-based Django setup based on gunicorn. On accessing admin it is not loading css/js files. The settings.py looks like below: # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' -
I am tryinng to create a comment box with django in which user profile picture have to show but i dont know to do this / i have tried something
comment box with user and user profile picture I am tryinng to create a comment box with django in which user profile picture have to show but i dont know to do this / i have tried something models.py class comments(models.Model): sno = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) post = models.ForeignKey(article, null=True, on_delete=models.CASCADE) comment = models.TextField(max_length=255) user_dp = models.OneToOneField(profilepic, null=True, on_delete=models.CASCADE) timedate = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.comment + " by " + self.user.name views.py def postcomment(request): if request.method == "POST": comment = request.POST.get("comment") user = request.user postSno = request.POST.get("postSno") post = article.objects.get(sno= postSno) user_dp = comment = comments(comment = comment, user = user, post = post, user_dp=user_dp) comment.save() print("comment saved") return redirect(f"/readfull/{post.slug}") html % for comnt in feedback %} <ul class="list-unstyled" style="margin: 5px;"> <li class="media" style="padding: 0px;"> <img src="{{media_url}}{{ comnt.user_dp.propic }}" class="card-img-top profilePic" alt="DP" style="width:50px; height:50px;"><br><br> <div class="media-body" style="padding: 0px;"> <p class="mt-0 mb-1 list-group-item list-group-item-info" id="commentname">{{comnt.user.name}}</p> <p class="card-text list-group-item list-group-item-secondary" id="comment" >{{comnt.comment}} <button type="button" class="close" aria-label="Close"> <span aria-hidden="true">&times;</span> </button><br><span id="timedate">{{comnt.timedate}}</span></p> </div> </li> </ul> {% endfor %} -
Why is not displayed Field average_rank?
The Problem is I get response without field average_rank my serializer.py is: class CarSerializers(serializers.ModelSerializer): average_rank = serializers.DecimalField(decimal_places=1,max_digits=10,read_only=True) class Meta: model = Car fields = ['Make_Name','Model_Name','average_rank'] And I get response : { "Make_Name": "Honda", "Model_Name": "Civic" }, without Average_rank field my views.py is: class RatingViewSet(ListCreateAPIView): serializer_class = RatingSerializer def get_queryset(self): queryset = Car.objects.all() queryset = queryset.annotate(average_rank = Avg('ratings__rating')) return queryset and Models.py : class Car(models.Model): Make_Name = models.CharField(max_length=100) Model_Name = models.CharField(max_length=100) class Rating(models.Model): RATING_CHOICES = ( (1,1), (2,2), (3,3), (4,4), (5,5), ) rating = models.IntegerField(choices=RATING_CHOICES) car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='ratings') -
How can I use google translation API in Django with python
I am using Django to create a project where I can change the language of website where user can use the page in any language they are comfortable with. But I am not sure how to implement google translate API in Django can anyone help me. I know that we can install google translation API using "$ pip install googletrans" but how can we implement this in Django framework. I am new to python. Thank you in advance. -
How to create a Class Based Views search bar on Django
I'm making a search bar in Django using Class-Based Views on my Views.py. When I try to get the value submitted in the input it's not showing the query name and if I don't submit anything is NOT giving me an error. Also what is the way to get the post showed by the world searched? Thanks for all. My code is: Models.py: class Post(models.Model): # Post core title = models.CharField(max_length=299) author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE) category = models.CharField(max_length=50) image = models.ImageField(blank=True) desc = models.TextField() text = RichTextField(blank = True, null = True ) date = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(null = True, blank = True, unique=True) class Meta: # Order post by date ordering = ['-date',] def __str__(self): # Display title return self.title def get_absolute_url(self): # #TODO da cambiare return reverse("listpost") Views.py: class SearchView(TemplateView): model = Post template_name = "admin/search.html" def get(self, request, *args, **kwargs): q = request.GET.get('q', '') self.results = Post.objects.filter(text__icontains=q, desc__icontains = q, title__icontains = q) return super().get(request, *args, **kwargs) Urls.py: path('dashboard/listpost/search/', SearchView.as_view(), name="search") ListPost.html: {% extends "admin/layout.html" %} {% block title %} <title>Post List</title> {% endblock title %} {% block content %} <form action="{% url 'search' %}" method="GET"> <input type="text" placeholder="Cerca" name="search"> <button>Cerca</button> </form> <div class="postlist"> <div … -
django orm queryset - to perform sql query MIN/MAX FILTER
I am trying to get help to create django ORM queryset for the particular sql statement (you can also run it here) https://dbfiddle.uk/?rdbms=postgres_13&fiddle=31c9431d6753e2fdd8df37bbc1869e88 In particular to this question, I am more interested in the line that consist of: MIN(created_at::time) FILTER (WHERE activity_type = 1) as min_time_in, MAX(created_at::time) FILTER (WHERE activity_type = 2) as max_time_out Here is the whole sql if possible to convert to django ORM queryset SELECT created_at::date as created_date, company_id, employee_id, MIN(created_at::time) FILTER (WHERE activity_type = 1) as min_time_in, MAX(created_at::time) FILTER (WHERE activity_type = 2) as max_time_out FROM timerecord where date(created_at) = '2020-11-18' and employee_id = 1 GROUP BY created_date, company_id, employee_id ORDER BY created_date, employee_id -
Django_Tables2 Dynamic Columns with Filters
Goal was to implement a simple View for the Users to Select columns dynamically with some added calculated info (annotations on some specific columns) and also let them filter on fields. Thankful for any comments, since this took me quite a few hours to get it working properly I thought I would provide a short writeup for anyone looking at a similar problem :) Used Modules/Libraries etc: Django-Filter Django_Tables2 Bootstrap-Select to properly display Multiple Choice Fields Example Model which we would like to use: class Summary(models.Model): billing_date = models.DateField(verbose_name='Billing Date') period = models.CharField(max_length=10, verbose_name='Period') operator = models.CharField(max_length=50, verbose_name='Operator') product = models.CharField(max_length=30, verbose_name='Product') ... -
How to gracefully handle auto disconnect of Daphne websockets
Daphne has a parameter --websocket_timeout link. As mentioned in the doc, --websocket_timeout WEBSOCKET_TIMEOUT Maximum time to allow a websocket to be connected. -1 for infinite. The socket is disconnected and no further communication can be done. However, the client does not receives a disconnect event, hence cant handle it gracefully. How does my client get to know whether the socket is disconnected or not?? I don't want to keep (at client) a timer nor want to keep rechecking it. Whats the right way to go about it,.?? -
Input string recognise text and return date parse
I have a string input where text contains data as "monday of next month" or "4 days before new year" need to convert into dates as suppose today is 25/11/2020, so next month monday is on 07/12/2020, so how should i do it in python (i've tried using datetime, dateutil but didn't help') next week saturday 4 days before new year 3 days after new year second wednesday of next month i need output as 05/12/20 28/12/20 03/01/21 09/12/21 tried reading docs but didn't help can anyone shed some light on it. -
Loop over serializer.is_valid in Django
I am trying to send payload as a list of dictionaries in views and save all of them but only the last item of dictionary gets through the serializer. Views.py for i in payloads: print("i", i) serializer = PFEPSerializer(data=i) if serializer.is_valid(): serializer.save() os.remove('filename.xlsx') return Response(status=status.HTTP_201_CREATED) To see the error I printed the validated_data in the serializer but it too shows the last item in the list. why is if serializer.is_valid(): serializer.save() not working for every loop and how can I do this? -
Please solve this im getting this error when i am trying to fetch "sr" value from my post named model
ValueError at /blog/postcmt Field 'sr' expected a number but got ''. Request Method: POST Request URL: http://127.0.0.1:8000/blog/postcmt Django Version: 3.1.3 Exception Type: ValueError Exception Value: Field 'sr' expected a number but got ''. Exception Location: C:\djangoproj\Blogwebsite\myprojenv\lib\site-packages\django\db\models\fields_init_.py, line 1776, in get_prep_value Python Executable: C:\djangoproj\Blogwebsite\myprojenv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\djangoproj\Blogwebsite', 'c:\users\admin\appdata\local\programs\python\python38\python38.zip', 'c:\users\admin\appdata\local\programs\python\python38\DLLs', 'c:\users\admin\appdata\local\programs\python\python38\lib', 'c:\users\admin\appdata\local\programs\python\python38', 'C:\djangoproj\Blogwebsite\myprojenv', 'C:\djangoproj\Blogwebsite\myprojenv\lib\site-packages'] Server time: Wed, 25 Nov 2020 09:22:46 +0000 -
Paginator returns a wrong number for next page in django
I am trying to add the pagination functionality on my blog page and it worked in theory but I don't understand why when it comes to give me text page number or the previous is giving something like this in the url: http://localhost:8000/blog/?page=%3Cbound%20method%20Page.next_page_number%20of%20%3CPage%201%20of%202%3E%3E I now that the Page.next_page_number should return me the next number of the next page, but it doesn't, here is my class based view: class BlogListView(generic.ListView): model = Page template_name = 'pages/blog_list.html' paginate_by = 1 def get_queryset(self): return Page.objects.filter(blog_post=True).order_by('-created_dt') and the rendering template {% extends 'j2base.html' %} {% block breadcrumb %} <h6 class="breadcrump"> <a href="/"><i class="fa fa-home"></i></a> <i class="fa fa-chevron-right"></i> Blog </h6> {% endblock breadcrumb %} {% block content %} <h1>BLOG</h1> {% if page_list %} {% for page in page_list %} <div class="blog_post"> <div class="blog_a"> <a href="{% url 'blog_page' page.slug %}">{{ page.title }}</a> </div> <div class="blog_body"> {{page.formatted_markdown|safe}} </div> <div class="blog_date"> Published {{ page.created_dt }} </div> </div> {% endfor %} {% else %} <p>There are no pages yet.</p> {% endif %} {% if page_obj.has_previous %} <!-- <a class="btn btn-outline-info mb-4" href="?page=1">First</a> --> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" … -
How to mock function call inside other function using pytest?
def publish_book(publisher): # some calculations factor = 4 print('xyz') db_entry(factor) # db entry call which I want to mock print('abc') def update(): publish_book('xyz') @pytest.mark.django_db def test_update(mocker): # in here I'm unable to mock nested function call pass I have db_entry() function call in publish_book(). how can we mock db_entry() function call inside publish_book.I want to perform other calculations of publish_book(), but only skip(mock) the db_entry() call. -
Git bash stopped after trying to push local database
I want to deploy a django project to heroku, so I moved the data in my sqlite database to data.sql in my project folder. I'm trying to push it to the database in heroku, but after this happened, git bash just stopped(not closed). Why is this happening? ssamt@DESKTOP-79IBIQ6 MINGW64 /c/(path to my django project) (master) $ heroku pg:push data HEROKU_POSTGRESQL_TEAL -a (my app name) heroku-cli: Pushing data ---> postgresql-rigid-46893 I can still type stuff, but nothing happens. -
How do I make a collaborative workspace with Django with my friends? [closed]
My friends and I, are working on an e-commerce website and now we need to work on the back-end using Django. We are new beginners with almost zero knowledge of Django. How can I make sure that the changes I make here on our website will also reflect on their files? We used to edit our files using a shared drive on OneDrive but Django runs on the cmd, so, I'm not sure how to make this happen. Anyone help us, soon??? -
Django - Get objects from the table which do not have a Foreignkey in another table
I am Django rest framework to return the list of objects who do not have a foreign key in another table. what queryset should I write to get those objects. models.py class Event(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=100,default='') description = models.TextField(blank=True,default='', max_length=1000) link = models.URLField(null=True) image = models.ImageField(null=True, blank=True) organizer = models.CharField(max_length=100, default='') timings = models.DateTimeField(default=None) cost = models.IntegerField(default=1,null=True,blank=True) def __str__(self): return self.title class Featured(models.Model): event = models.ForeignKey(Event, null=True ,on_delete=models.PROTECT, related_name="event") def __str__(self): return self.event.title class Meta: verbose_name_plural = 'Featured' views.py class Upcoming2EventsViewSet(mixins.RetrieveModelMixin,mixins.ListModelMixin,viewsets.GenericViewSet): serializer_class = Upcoming2Events def get_queryset(self): featured_events = Featured.objects.all().values_list('id') return Event.objects.filter(id__in=featured_events) # return Event.objects.exclude(id__in=featured_events.event.id) # # return Event.objects.exclude(id__in = [featured_events.id]) serializers.py class Upcoming2Events(serializers.ModelSerializer): id = serializers.CharField(source='event.id') title = serializers.CharField(source='event.title') timings = serializers.DateTimeField(source='event.timings') organizer = serializers.CharField(source='event.organizer') class Meta: model = Featured fields = ['id','title','organizer','timings'] Error Got AttributeError when attempting to get a value for field `id` on serializer `Upcoming2Events`. The serializer field might be named incorrectly and not match any attribute or key on the `Event` instance. Original exception text was: 'RelatedManager' object has no attribute 'id'. Can you tell me what queryset should I write to get the only objects which are not present in the table Featured? Also, what should I do to get only the … -
how to implement branch wise permission in Django
This question is concerned about role and permission in DJango.I am developing web CRM for a company who have multiple branches. But the problem a staff may have multiple role in each branches. That mean Satff x will be working as 'branch manager' at branch-1 and also will be work as 'sales manager' at branch -2. Both roles are different permissions, and also user should be able to customize permission of each user even though they are belongs to role. I thought to implement this Django Group, Permission options, I have created staff by extends User,Please help me to design its model effectively. from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from branch.models import Branch from django.contrib.auth.models import Group from django.contrib.auth.models import Permission class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" … -
In template /home/ryszardb/Desktop/classProject/config/templates/base.html, error at line 0
<!-- templates/forages/project_list.html --> {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} <div class="welcome-user" style="color:darkcyan; text-align:center; font-size: x-large;"> <h1>Welcome {{ user.username }}</h1> </div> {% for project in object_list %} <div class="card"> <div clas="card-header"> <span class="font-weight-bold"><a href="{% url 'project_detail' project.pk %}">{{ project.title }}</a></span> &middot; <span class="text-muted">by {{ project.author }} | {{ project.date }}</span> </div> <div class="card-body"> {{ project.description }} <a href="{% url 'project_edit' project.pk %}">Edit</a>| <a href="{% url 'project_delete' project.pk %}">Delete</a> </div> <div class="card-footer"> {% for entry in project.entries.all %} <p> <span class="font-weight-bold"> {{ entry.author }} &middot; </span> {{ entry }} | longitude: {{ entry.longitude }} | laditude: {{ entry.latitude}} </p> {% endfor %} </div> <div class="card-footer text-center text-muted"> </div> </div> {% endfor %} {% else %} <h1 style="color:darkcyan; text-align: center; font-size: xx-large;"> Please Sign-In before viewing. <br/> Thank you :)</h1> {% endif %} {% endblock content %} <!--- templates/forages/project_detail.html --> {% extends 'base.html' %} {% block content %} <div class="project-detail"> <h2>{{ project.title }}</h2> <p> by {{ project.author }} | {{ project.date }}</p> <p>{{ project.description }}</p> </div> <p><a href="{% url 'project_edit' project.pk %}">Edit</a></p> <p><a href="{% url 'project_delete' project.pk %}">Delete</a></p> <p>Back to <a href="{% url 'project_list' %}">All projects</a></p> {% endblock content %} #urls.py from django.urls import path from .views … -
How much websocket connection can one daphne handle at the same time and how can I increase the max connection
I have 10 daphne instances running When I try to connect 400 clients, only a few connection lost. When I try to connect 1000 clients, more than 400 connection lost. from channels.consumer import SyncConsumer,AsyncConsumer from websocket.utils import * from asgiref.sync import async_to_sync import threading import time #from channels_presence.models import Room #from channels_presence.models import Presence class Consumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", 'text': "testtt" }) async def websocket_disconnect(self, close_code): #Room.objects.remove("some_room", self.channel_name) pass Django==2.2.8 channels==2.3.1 channels-redis==2.4.1 psycopg2==2.8.5 daphne==2.5.0 django-channels-presence settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
how to add days to django annotate from already built annotation
my model looks like this class Model(models.Model): user_id = models.ForeignKey() date = models.DateField() field1 = models.FloatField() field2 = models.FloatField() I have a below queryset queryset = Model.objects.filter(user_id__exact=5) \ .annotate(weekstartdate=Trunc('date', 'week')) \ .values('weekstartdate') \ .annotate(avg_distance=Avg('field1')) \ .annotate(avg_speed=Avg('field2')) \ .order_by('-weekstartdate') which is working perfectly. now I want to add weekenddate field to above queryset which has a date = weekstartdate + 6 days. I have added below line to above query .annotate(weekenddate=Trunc('date', self.duration) + timedelta(days=7), output_field=DateField()) but it is complaining :- TypeError: QuerySet.annotate() received non-expression(s): <django.db.models.fields.DateField> Relative imports from django.db.models import Avg, Q from django.db.models.functions import Trunc from django.db.models import DateTimeField, ExpressionWrapper, F, DateField -
Exception inside application: You cannot call this from an async context - use a thread or sync_to_async
I have been using django-channels, I had created a room for 2 users using single thread from django.db import models from django.contrib.auth import get_user_model from django.db.models import Q from channels.db import SyncToAsync # Create your models here. model = get_user_model() class threadmanager(models.Manager): def get_or_create(self,firstuser,seconduser): thread = self.get_queryset().filter(((Q(first=firstuser)and Q(second = seconduser ))) or ((Q(first=seconduser)and Q(second = firstuser )))) if thread: print(thread.first()) return thread thread = self.model(first=firstuser,second=seconduser) thread.save() return(thread) class thread(models.Model): first = models.ForeignKey(model,on_delete=models.CASCADE,related_name="first") second = models.ForeignKey(model,on_delete=models.CASCADE,related_name="second") objects = threadmanager() def __str__(self): return self.first.username + "-" + self.second.username My chatconsumer is from channels.consumer import AsyncConsumer import asyncio from channels.db import database_sync_to_async import json from accounts.models import thread from django.contrib.auth import get_user_model model = get_user_model() class ChatConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send( { 'type':'websocket.accept', } ) print("connected",event) async def websocket_receive(self,event): print("received",event) firstuser,seconduser = await self.get_socket_users(event) currentthread = await self.get_current_thread(firstuser,seconduser) print(currentthread) async def websocket_disconnect(self,event): print("disconnected",event) @database_sync_to_async def get_socket_users(self,event): first = self.scope['user'] second = model.objects.get(username=event['text']) return first,second @database_sync_to_async def get_current_thread(self,firstuser,seconduser): return thread.objects.get_or_create(firstuser,seconduser) Whenever i am trying to create a new thread between 2 users i am successfully getting it: for example my first user is root and second user is rusker. WebSocket HANDSHAKING /profile [127.0.0.1:35432] WebSocket CONNECT /profile [127.0.0.1:35432] connected {'type': 'websocket.connect'} received {'type': 'websocket.receive', … -
Issue on Updating a record in Django crispy Form
The issue is while editing the record its give DoesNotExist at /4/ > views.py from django.shortcuts import render,redirect from .forms import StudentForm,StudentForm_Timeline from .models import Student_details,Student_details_Timeline from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.contrib import messages from django.http import Http404 # Create your views here. # for student details @login_required(login_url='login') def student_list(request): student_details = Student_details.objects.all().order_by('id') paginator = Paginator(student_details,3,orphans =1) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'page_obj' : page_obj} return render(request, 'dashboard/student_list.html',context) @login_required(login_url='login') def student_form(request,id=0): if request.method == 'POST': if id == 0: form_student = StudentForm(request.POST) else: student = Student_details.objects.get(pk=id) form_student = StudentForm(request.POST,instance=student) messages.info(request,'Record Updated Successfully!') if form_student.is_valid(): form_student.save(force_update=True) return redirect('student') else: if id == 0: form_student = StudentForm() else: student = Student_details.objects.get(pk=id) form_student = StudentForm(instance = student) context = {'form_student': form_student} return render(request, 'dashboard/student_form.html',context) def student_delete(request,id): student = Student_details.objects.get(pk=id) student.delete() messages.info(request,'Record Deleted!') return redirect('list') # for student timeline @login_required(login_url='login') def timeline_list(request): student_timeline = Student_details_Timeline.objects.all().order_by('id') paginator = Paginator(student_timeline,5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'page_obj' : page_obj} return render(request, 'dashboard/timeline_list.html',context) @login_required(login_url='login') def timeline_form(request,id=0): if request.method == 'POST': if id == 0: form_timeline = StudentForm_Timeline(request.POST) else: student = Student_details_Timeline.objects.get(pk=id) form_timeline = StudentForm_Timeline(request.POST,instance=student) messages.info(request,'Record Updated Successfully!') if form_timeline.is_valid(): form_timeline.save(force_update = True) return redirect('timeline') else: if id == … -
How to stop django-html formatting to one line with tags
When I save my django-html file the following changes occur in auto formatting. {% extends 'base.html' %} {% block content %} {% if dice %} {% for die in dice %} <img src="{{die.image.url}}" alt="{{die.name}}" /> {% endfor %} {% endif %} {% endblock %} I want to have something like the following instead... {% extends 'base.html' %} {% block content %} {% if dice %} {% for die in dice %} <img src="{{die.image.url}}" alt="{{die.name}}" /> {% endfor %} {% endif %} {% endblock %} I have Beautify installed and my settings are as follows... "emmet.includeLanguages": { "javascript": "javascriptreact", "django-html": "html" }, "files.associations": { "**/*.html": "html", "**/templates/*/*.html": "django-html", "**/templates/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "beautify.language": { "html": ["htm", "html", "django-html"] },