Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web deployed by pythonanywhere doesn't refresh automatically [closed]
I deployed my Django project with pythonanywhere and have already pushed it from localhost to the webserver. My Django project is linked with dynamic data from my google sheet API. However, when I edit on my google sheet and reload the page, the data doesn't change accordingly. I have to manually click the "reload" button on pythonanywhere to refresh my data. Does anyone know what should I do? -
How to post data to ModelForm while testing assertRedirects
I try to test correct redirect after post data with ModelForm. In my view if form.is_valid() equals True, form is saved and view redirects to homepage. My test_forms.py looks like this: class TestForms(TestCase): def setUp(self): # imitacja witryny self.client = Client() self.tag = Tag.objects.create( name='Bull flag' ) self.data = { 'ticker': 'FB', 'exchange': 'NASDAQ', 'buy_point': 121, 'stop_loss': 120, 'description': 'ciamciaramcia', 'tags': [self.tag] } self.form = StockTradeForm(self.data) def test_stock_trade_form_valid_data(self): self.assertTrue(self.form.is_valid()) # OK self.form.save() self.assertEqual(StockTrade.objects.count(), 1) # OK after self.form.save() self.assertTrue(StockTrade.objects.filter(ticker='FB').exists()) # OK after self.form.save() def test_stock_trade_form_valid_redirect(self): response = self.client.post(reverse('create-trade'), self.data) print(response) # print result: .<HttpResponse status_code=200, "text/html; charset=utf-8"> self.assertTemplateUsed(response, 'journal/create_trade.html') # OK self.assertEquals(response.status_code, 200) # OK self.assertRedirects( response, reverse('index'), status_code=200 ) # Failure: # in assertRedirects # url = response.url # AttributeError: 'HttpResponse' object has no attribute 'url' Shouldn't response = self.client.post(reverse('create-trade'), self.data) imitate valid and saved form? My view name is: create_trade Url looks like this: urlpatterns = [ path('', views.index, name='index'), path('display-trade/<str:pk>', views.display_trade, name='display-trade'), path('create-trade', views.create_trade, name='create-trade'), path('update-trade/<str:pk>', views.update_trade, name='update-trade') ] I'm concerned about this two tests self.assertTemplateUsed(response, 'journal/create_trade.html') # OK self.assertEquals(response.status_code, 200) # OK Is it correct that after self.client.post assertTemplateUsed response is equal 'journal/create_trade.html' and status_code is 200? I tried many things with self.client.post but nothing work … -
Django howto progessively write data into a huge zipfile FileField
I have a django model like this: class Todo(models.Model): big_file = models.FileField(blank=True) status = models.PositiveSmallIntegerField(default=0) progress = models.IntegerField(default=0) I'd like to do two operations: first make an empty zipfile out of big_file (less important) and then progressively add files into my zipfile (and save it iteratively) The overall process would look like that: from django.core.files.base import File import io, zipfile def generate_data(todo): io_bytes = io.BytesIO(b'') # 1. save an empty Zip archive: with zipfile.ZipFile(io_bytes, 'w') as zip_fd: todo.generated_data.save('heavy_file.zip', File(zip_fd)) # 2. Progressively fill the Zip archive: with zipfile.ZipFile(io_bytes, 'w') zip_fd: for filename, data_bytes in long_iteration(todo): with zip_fd.open(filename, 'w') as in_zip: in_zip.write(data_bytes) if condition(something): todo.generated_data.save() # that does not work todo.status = 1 todo.progress = 123 todo.save() todo.status = 2 todo.save() But I can't figure out the right filedescriptor / file-like object / Filepath / django-File object combination ... And it seems that in django I always have to save(filename, content). But my content could be Gigabytes, so it does not sound reasonable to store it all into a "content" variable? -
Django 'this field is required' form error on non-editable field
I'm trying to build a form that lets me categorise/edit my bank transactions. Ideally all uncategorised transactions will be displayed on one page (in a formset) and I'll be able to edit some/all of them. When I hit 'submit' on the formset, I want to save any changes and navigate to a confirmation page. Here's my model for a Transaction: class Transaction(models.Model): description = models.CharField(max_length=200) post_date = models.DateTimeField('date') account = models.ForeignKey(Account, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) amount = models.DecimalField(max_digits=9, decimal_places=2) uuid = models.CharField( max_length=200, primary_key = True, unique = True, editable=False) def __str__(self): return self.description Date, description, and amount are important to show on the form because they help me figure out how to categorise the transaction. I don't want to accidentally edit the date or amount, so I've made them readonly on the form. Transactions also have uuid and account fields, but those are irrelevant to categorisation and I don't want to edit them, so they shouldn't be shown at all. My form and formset look like this: class TransactionForm(ModelForm): class Meta: model = Transaction exclude = ('uuid', 'account') def __init__(self, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) cat = self.fields['category'] cat.required = False cat.blank = True self.fields['description'] self.fields['amount'].readonly … -
save() prohibited [...] due to unsaved related object, but related object already saved
I'm working with Django 4.0.1. I'm having having "save() prohibited to prevent data loss due to unsaved related object 'page'" even if the 'page' object is saved one line before. Here is the code: # Upload entity data u = Upload( message=request.POST["upload_msg"] ) # saving u here to be able to use u.datetime later u.save() # new page for the upload entity page = Page( title="notes for Upload " + str(u.datetime), content="This page is empty..." ) page.save() u.page = page u.save() The last line (u.save()) is the one causing the error. Am I having some kind of race condition here? Isn't it assured that the previous db operations are complete before trying to run the next? Any other ideas? Thank you. -
Virtual Trading Platform with Django Rest Framework (Good Idea)?
Trading application relies on many requests is it advisable to build the API backend with Django rest framework with scalability in mind? Any suggestions would be great. -
ListView with an extra argument
I want to add a parameter somevar to my listview: {% url 'products' somevar %}?" in the urls: path("products/<int:somevar>", ProductListView.as_view(), name = 'products'), in the views: class ProductListView(ListView): def get_template_names(self): print(self.kwargs) # {"somevar": xxxxx} return f"{TEMPLATE_ROOT}/products.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_products().order_by("number") print(kwargs) # kwargs is {} here return context def get_queryset(self): return super().get_queryset().order_by("number") How can I pass the variable to the get_context_data method? I tried defining a get method and call self.get_context_data(**kwargs) within, but this leads to an object has no attribute 'object_list' error. -
Ajax not getting data from Django view
I have a page that the user is supposed to type in the URL to a YouTube video. That URL is sent with Ajax to a Django view that checks the URL to see if its valid or not. Then it alerts with either an error message is if its not valid, or alerts with the video title if it valid. The alerts are done with the standard javascript alerts. This is just a test version of the page. I plan to display the info gathered from video on the page itself. This is the template for the page. <body> <form method="post"> {% csrf_token %} <input type="text" name="url" id="url"> <label for="url">Please Enter Video URL Below</label> <button id='button'></button> <p id = 'test'></p> </form> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <script> document.getElementById('button').addEventListener('click', find_video, false) function find_video(){ var url = document.getElementById('url').value; $.ajax({ url: "ajax/find_video/", type: "POST", data: { csrfmiddlewaretoken: window.CSRF_TOKEN, url : url}, dataType: 'json', complete: function(data){ if (data.error_message){ alert('Please enter valid url') } else { alert(data.video_title) } }, }); } </script> </body> </html> This is the Django view def find_video(request): url = request.POST.get('url') #unquotes url formating so youtube_dl can use it. urllib.parse.unquote(url) if is_valid(url): error_message = False else: … -
Django Save User Responses for Next Visit - Caching or Sessions?
I have a user review system where managers can review their employees access to specific systems. The table they are presented with looks something like this <table class="employeeTable" id="employeeTable"> <thead> <tr> <th>Status</th> <th>Employee Name</th> <th>PID</th> <th>Title</th> <th>Email</th> <th>Enabled in System</th> <th>System Permission Group</th> <th>System Name</th> <th>Approve</th> <th>Deny</th> <th>Reasoning</th> </tr> </thead> <tbody> <tr> <td class="statusCircle" accessCorrect="False"><svg class="statusCircle" style="margin-left:5px;" xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="grey" stroke="#be9b9b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle></svg></td> <td>Last, First</td> <td>Emp ID</td> <td>Emp title</td> <td>first.last@email.com</td> <td>true</td> <td>Permissions</td> <td>System Emp ID</td> <td class="approvePerm"><svg class="approvePerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#43a600" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg></td> <td class="denyPerm"><svg class="denyPerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#d90e0e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></td> <td><select class="reason" style="display: none;"> <option>No longer employed with Company</option> <option>Job role no longer requires this access</option> <option>Employee has transferred</option> </select></td> </tr> <tr> <td class="statusCircle" accessCorrect="False"><svg class="statusCircle" style="margin-left:5px;" xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="grey" stroke="#be9b9b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle></svg></td> <td>Last, First</td> <td>Emp ID</td> <td>Emp title</td> <td>first.last@email.com</td> <td>true</td> <td>Permissions</td> <td>System Emp ID</td> <td class="approvePerm"><svg class="approvePerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#43a600" … -
First time deploying a django app on Heroku and I'm facing 2 issues, solution?
I've worked on my social app and been able to deploy it and I'm having 2 problems: Link: https://network50web.herokuapp.com/ 1/It directs me autmatically to https://network50web.herokuapp.com/accounts/login/?next=/ and I'm only able to see the site if I write the routes manually in the address bar like(login, register) 2/When I try to login it with my existent username it throws error "Programming Error at /login relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user..." and it highlights this line " user = User.objects.create_user(username, email, password)" even when I try to register a new account I used SQL for the database Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect, request from django.http.response import JsonResponse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.urls import reverse, reverse_lazy from django.core import serializers from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from itertools import chain from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm def search_view(request): if request.method == "POST": searched = request.POST['searched'] profiles = Profile.objects.filter(slug__contains=searched) return render(request, … -
Django displaying uploaded images
I am working on an application that allows users to upload PDFs. I want to display the PDFs in various templates. I am using multi-tenant so that may be an issue. So far, I haven't been able to get the PDFs to display. In the place of the image I see: Page not found (404) Request Method: GET Request URL: http://co1.localhost:8000/projects/project/1/document/2/projects/documents/012022/Joint1021S.pdf The view: class ProjectDocumentsDetailView(DetailView): model = ProjectDocuments id = ProjectDocuments.objects.only('id') template_name = 'company_accounts/project_document_detail.html' The template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ projectdocuments.title }}</h2> <p>{{ projectdocuments.description | safe }}</p> <embed src="{{ projectdocuments.file }}" <img src="{{ projectdocuments.file }}"> <p>{{ projectdocuments.file }}</p> </div> <div> </div> {% endblock content %} In the main site config/urls I have the line: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The files (in this specific instance) are stored in a file in media>company1>documents>012022>file.pdf From the error, at least one issue appears to be the way the path to the pdf is being constructed. Any ideas about how to fix this? -
Show request duration in drf-spectacular (Swagger)
I have a Django/DRF project with drf-spectacular (Swagger) integration and wondering how can I add a request duration as shown on the image below. Is there any way to achive elapsed time section? Thanks in advance. -
Django Rest Framework: how to route a uuid to an associated object?
I am building a simple photos-albums app with Django Rest Framework (DRF). Each album has a UUID field in its model. I want to create 'share links' so that someone with a link of the form /albums/[uuid] will be able to access that album. I am using ModelViewSet for my views, so I assume that the most succinct way to achieve this desired routing is via the action decorator, with urls like /albums/shared/[uuid], but it's not clear to me how to obtain the uuid in the action-decorated shared method. I can't even parse the URL because DRF will 404 before firing this shared method: ### views/album.py class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer @action(detail=False, methods=['get']) def shared(self, request): # How do you get the uuid from the supplied URL? uuid = ??? obj = self.get_queryset().objects.get(uuid=uuid) return Response([obj]) Hopefully I won't have to add any fancy patterns to urls.py, but if I do then here is what I have so far: ### myapp/urls.py router = routers.DefaultRouter() router.register(r'albums', AlbumViewSet) ... urlpatterns = [ # ... path('', include(router.urls)), ] format_suffix_patterns(urlpatterns) Thanks! -
How to add data to a ManyToMany field model?
I have model Department: class Department(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name') superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING) manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING) history = HistoricalRecords() def get_subsidiary(self): return "\n".join([p.title for p in self.subsidiary.all()]) def __str__(self): return self.title In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary. I want to implement next logic: I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically. I am trying to override save method like: def save(self, *args, **kwargs): print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior)) if self.superior__in == Department.objects.filter(title=self.superior.title): tmp = Department.objects.filter(title=self.superior.title) tmp.create(subsidiary = self.superior) tmp.save() super(Department, self).save(*args, **kwargs) But it doesn't work. How can implement something like this? -
Python Django DLL load failed: %1 is not a valid Win32 application
I have a 64 bit architecture system. I installed Python 3.6.0. Project was building and model was compile successfully, but when I install VS Code and install some extensions. My Django Bankend is not working and shown an error:"DLL load failed: %1 is not a valid Win32 application." Any suggestions? -
trying to create a row on a table after making a POST -django
How can I create a new row in table notificacao everytime i make this post? (save is not working i get 'QuerySet' object has no attribute 'save') def post(self, request): cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf']) cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf']) notificacao1 = Notificacao.objects.all() if cliente1.saldo >= request.data['quantia']: cliente1.saldo -= request.data['quantia'] cliente1.save() cliente2.saldo += request.data['quantia'] cliente2.save() notificacao1.cpf_remetente = request.data['cliente1_cpf_transf'] notificacao1.cpf_destinatario = request.data['cliente2_cpf_transf'] notificacao1.valor = request.data['quantia'] notificacao1.save() -
How to stop SQL injection in Django column of a model
So I know that Django naturally handles sql injections for columns in tables but my team want to do more. We have a help_message table in Django and there is a column in that table called Message which is a string. We do not want to save that message directly as a string in that column because of possible sql injection and malicious use. What can we do to stop sql injection and save that message in the table in Django? -
How exactly does a generic view like DeleteView make your app more scaleable in Django?
My app is currently built exclusively on function-based views, and I'm looking into class based views and especially the generic ones to make it more scaleable - as this is recommended many places. For the class based views in general, I can see the utility as opposed to hundreds of function based views. However - I'm having trouble seeing how the generic ones do anything to save time. I'm trying to figure out the DeleteView now, and it seems to be actually adding more complexity to my code. Currently, a deletion view for me looks like this: views.py def fruit_delete(request, num): fruit = fruits.objects.filter(pk=num) fruit.delete() return redirect(fruits) And all I need to add is a path: urls.py path('fruit_delete/<int:num>', views.fruit_delete, name='fruit_delete'), And a easily replicated button in my templates: <a class="btn btn-danger" href = "{% url 'fruit_delete' fruit.pk %}" onclick="return confirm('Are you sure you want to delete this fruit?')">Delete</a> And this does the job. If I was to need a hundred or so of those views however, it would be beneficial to be able to use the model in question, or other parameters, as arguments in the template itself instead of having to create a separate view + path for every … -
Making a change/Replace the text in a file at specific places in python
I need your help. Currently, I'm developing a Django automation script that will be useful in the future. However, I am unable to replace a specific code snippet with my updated code snippet. Updated code snippets are written at the end of the file, doubling the code snippet in the same file. You can see the code that we (me and Github Copilot) wrote together import os project_name = str(input("Whats your project name : ")).capitalize() apps_name = str(input("What your apps name : ")).split(",") # check if the project name is in the current directory if os.path.isdir(project_name): print("Project name is already in the current directory") exit() else: os.system('cmd /c "django-admin startproject ' + project_name) # change the directory to the project name os.chdir(project_name) # print the current directory print(os.getcwd()) # check if the apps name is in the project directory if os.path.isdir(apps_name[0].capitalize()): print("Apps name is already in the project directory") exit() else: # check if apps_name has more than one app if len(apps_name) > 1: for app in apps_name: os.system('cmd /c "django-admin startapp ' + app.capitalize()) else: os.system('cmd /c "django-admin startapp ' + apps_name[0].capitalize()) # change the directory to the project name os.chdir('../'+project_name) # print the current directory print(os.getcwd()) search_text = … -
How to access the values in nested dictionary sent to django template
I'm sending a nested custom dictionary through my views, that nested dictionary is 'history' def update_participation(request,user_id,event_id): ev=Event.objects.get(id=event_id) data=Participated(user=user_id,event=event_id) data.save() participated=Participated.objects.filter(user=user_id) i=0 #Declared the dictionary history history={} #Adding values to dictionary for partcipate in participated: name=Event.objects.get(id=partcipate.event) name1=name.name fest=Fest.objects.get(id=name.fest_id.id) fest1=fest.name clg=College.objects.get(id=fest.clg_id.id).name history[i]={'event':name1,'fest':fest1,'college':clg} i+=1 messages.success(request,f'You have registered for {ev.name}') #sending the dictionary to template return render(request,'webpage/my_events.html',history) Example of dictionary will look history={0={'event':'css battle','fest':'verve','college':'jss'},1={'event':'code wars','fest':'verve','college':'jss'},2={'event':'hangman','fest':'phase shift','college':'bms'}} I'm trying to access the values css battle,verve,jss like {%extends 'webpage/base.html'%} {%block content%} <h2 style="margin:5px 30px;"><u>My Event History</u></h2> <div style="margin:50px 0px 0px 270px" class='table'> <table border='5'> <tr> <th>Event</th> <th>Fest</th> <th>College</th> </tr> {%for key,value in history.items%} <tr> <td>{{value.event}}</td> <td>{{value.fest}}</td> <td>{{value.college}}</td> </tr> {%endfor%} </table> </div> {%endblock content%} How am I supposed to iterate through the dictionary? -
Django: email sender is the same as the recipient sender , How i can resolve that
I have developed a form contact where the user can contact us he will type his email, the subject and the message, But am stuck on after some tries I didn't succeed to reach my goal , everything is good the email is send to the email recipient that i have mentioned in settings.py EMAIL_HOST_USER But the email sender is registered as the email recipient i do no why ,Here is the code: def contact_view(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, [settings.EMAIL_HOST_USER]) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, 'pages/success.html') return render(request, 'pages/contact.html', {'form': form}) How i can resolve that i don't want the sender email be the recipient email , i want it to be the email that user will entered during fill out the form. -
Resolve dependency conflict with dash-bootstrap-components, dash, and django-plotly-dash 1.6.6
I am trying to build a docker image for a django web app that has dash and plotly components. However, my build fails with the following error The conflict is caused by: #11 39.72 dash-bootstrap-components 1.0.2 depends on dash>=2.0.0 #11 39.72 django-plotly-dash 1.6.6 depends on dash<1.21.0 and >=1.11 #11 39.72 #11 39.72 To fix this you could try to: #11 39.72 1. loosen the range of package versions you've specified #11 39.72 2. remove package versions to allow pip attempt to solve the dependency conflict I've tried loosening the ranges and removing package versions but am still getting the same error. After some research it appears django-plotly-dash is not updated for dash>2.0 Is there a work around? My webpage works fine locally so I'm not sure why building it is now having the issue. -
How to apply rich text features to the parent element in Wagtail DraftJS?
I am extending Wagtail's DraftJS editor: @hooks.register('register_rich_text_features') def register_uppercase_feature(features): feature_name = 'text-uppercase' type_ = 'UPPERCASE' tag = 'span' control = { 'type': type_, 'label': 'UP', 'description': 'Uppercase', 'style': {'text-transform': 'uppercase'}, } features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) db_conversion = { 'from_database_format': {tag: InlineStyleElementHandler(type_)}, 'to_database_format': {'style_map': {type_: 'span ' 'class="text-uppercase"'}}, } features.register_converter_rule('contentstate', feature_name, db_conversion) features.default_features.append('text-uppercase') The above code works well and applies a element around selected text: <h1><span class="text-uppercase">example text</span></h1> However, how I want to apply my feature to the parent element, h1, not add a span element: example text How can I inherit the parent element? -
I want to query 3 Random Products from the Database everytime only 3
y = (Product.objects.all()).count() x = random.randint(3,y) prouct1 = Product.objects.get(id = x+1) prouct2 = Product.objects.get(id = x-1) prouct3 = Product.objects.get(id = x-2) I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the database every time the page is renderd -
Conditionally highlight cells in a html table based on the cells' value
The data of my html table is from this list: mylist= [{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 }, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}] My HTML table in my HTML file is: <table class="table table-striped" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>StartDate</th> <th>ID</th> <th>Name</th> <th>Days</th> </thead> <body> {% for element in mylist %} <tr> <td>{{ element.StartDate}}</td> <td>{{ element.ID }}</td> <td>{{ element.Receiver }}</td> <td>{{ element.Days }}</td> </tr> {% endfor %} </tbody> </table> I want to set the color of days that are larger than 14 into Red color. And I want to set the cells that contain "Mike" in Red and "Jane" in Blue. Please advise what I should do