Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django - what is the best way to avoid doing repetitive queries in a dynamic navbar?
I'm currently developing a project which has two apps. When the user logs into the system, the navbar will show the links according to what permissions the user has in the database. If the user only has permissions for app 1, the links it will show will only correspond to this app, the same if it only has permission for app2. If the user has permission for both the navbar will show all the links of both apps. Being dynamic the navbar has to make queries to the database. so I want to avoid making a query every time a page is loaded. I have thought that an option is, in the view, to make the query a first time and then store it with request.session: Try: #If the query has already been made, it accesses the saved value query = request.session['navbar'] Except: # If the query has not been made, makes it and saves it in request.session['navbar'] request.session['navbar'] = #QUERYCODE This is a good way to handle the problem? is there another better way? - 
        
How to filter a query on Django ORM
I know this should be pretty basic but somehow I don't quite get it. I want to get all users which age is lesser than 18 so the query should be something like this User.objects.filter(age < 18) what Im doing wrong? - 
        
Django - If i put 2 formsets together in my view, the function to add multiple times the same views doesnt work
I have this code bellow. Im using formset to add multiple times the same form. But if i put this 2 formsets together, like in my view, just the first data for each form is saved. And if i put just 1 formset in my def, it works, all datas for i put to the form is saved. Someone have any idea why this is happening? (sorry for my eng) Forms.py class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] InsereIdiomaFormset = formset_factory(InsereIdioma, extra=1) class InsereTecnologia(forms.ModelForm): class Meta: model = Tecnologia fields = '__all__' exclude = ['usuario'] InsereTecnologiaFormset = formset_factory(InsereTecnologia, extra=1) Views.py def cadastro_curriculo(request): if request.method == 'GET': formset_idioma = InsereIdiomaFormset(request.GET or None) formset_tecnologia = InsereTecnologiaFormset(request.GET or None) elif request.method == 'POST': formset_idioma = InsereIdiomaFormset(request.POST) formset_tecnologia = InsereTecnologiaFormset(request.POST) if formset_idioma.is_valid(): for form in formset_idioma: idioma = form.cleaned_data.get('idioma') fluencia = form.cleaned_data.get('fluencia') if idioma and fluencia: Idioma( idioma=idioma, fluencia=fluencia, usuario=request.user ).save() if formset_tecnologia.is_valid(): for form in formset_tecnologia: sistema = form.cleaned_data.get('sistema') nivel = form.cleaned_data.get('nivel') if sistema and nivel: Tecnologia( sistema=sistema, nivel=nivel, usuario=request.user ).save() return render(request, "personal/curriculo.html", { 'formset_idioma': formset_idioma, 'formset_tecnologia': formset_tecnologia, }) - 
        
Post HTML input tag file data to another input tag file and retrieve in Django views
I'm trying to send one <input type="file"... value to another <input type="file".. using Javascript. I've created an HTML form and after filling it, I want to review the form. Then submit that form in my FormFill model through views.py. So far what I have done is creating 2 different Divs for the same work. In div1, I'm sending my form data using action="javascript:reviewForm()" and in reviewForm(), I'm setting all the form data of div1 to div2 form using document.getElementById('cfname2').value = document.getElementById('cfname1').value; It's setting all the values and then posting it to views.py successfully except my <input type="file" name="pic2".. data. Since python retrieves form POST data using request.FILES['pic2'], in div2 I don't have file data to Post. So far what I've tried is: document.getElementById('pic2').value = document.getElementById('pic1').value; where, In div1 I have <input type="file" id="pic1"... and in div2, <input type="file" id="pic2"... My models.py class FormFill(models.Model): pic = models.ImageField(upload_to='candidates/pics/') ... How can I post the div2 image data to views and then to Django models? Note: I don't want to Post the div1 data directly to Django models since I want my users to first review the form that they have filled. And that's why using the concept of 2 Divs. Thanks in … - 
        
Chaining querysets in managers
I am looking for a way to reuse this abstract model/manager with queryset on the models that require soft delete but some of my models already have custom managers/querysets. Ideally I would like all of those other managers to use SoftDelete manager/queryset so that they would always return only undeleted items. Is there a way to achieve this in Django 1.10? class SoftDeleteQuerySet(QuerySet): def delete(self): for obj in self: obj.is_active = False obj.save() def undelete(self): for obj in self: obj.is_active = True obj.save() class SoftDeleteManager(Manager): def get_queryset(): return SoftDeleteQuerySet(self.model, using=self._db).filter(is_active=True) class SoftDelete(Model): is_active = m.BooleanField(default=True) objects = SoftDeleteManager() class Meta: abstract = True def delete(self): self.is_active = False self.save() def undelete(self): self.is_active = True self.save() - 
        
KeyError when passing kwargs to ModelForm
I'm trying to create a custom field for my M2M field in my ModelForm. ConnectedTo is the many to many field. Code below: views: def addPartForm_Create(request, site, subtype): siteselected = site sitenumber = str(site) print(sitenumber) subtypeselected = Subtype.objects.get(SubtypeID = subtype) if request.method == 'POST': form = addPartForm(request.POST, sitenum=sitenumber) if form.is_valid(): obj = form.save(commit=False) obj.SiteID = Site.objects.get(SiteID = siteselected) obj.Subtype = subtypeselected obj.save() form.save_m2m() return redirect('/sites/'+str(site)) else: form = addPartForm() return render(request, 'myproj/addPart.html', {'form': form, 'SiteNo': Site.objects.get(SiteID = siteselected).SiteID, 'subtype': subtypeselected}) forms: class addPartForm(forms.ModelForm): class Meta: model = Part fields = ('Comment', 'Location', 'ConnectedTo', 'BatchNo', 'Manufacturer', 'Length', 'InspectionPeriod') labels = {"BatchNo": "Batch Number", "InspectionPeriod": "Inspection Period"} def __init__(self, *args, **kwargs): super(addPartForm, self).__init__(*args, **kwargs) sitenum = kwargs.pop('sitenum') self.fields["ConnectedTo"].widget = forms.CheckboxSelectMultiple() self.fields["ConnectedTo"].queryset = Part.objects.filter(SiteID = sitenum) I get KeyError when I try to pass sitenum from view to form. I know I could set a default value None but I don't want it to ever display none. I need to always have a sitenum sent here. Am I passing this wrong? - 
        
pytest, How do you break up rather long test?
I'm writing my first pytest test, and it is rather long (currently 120 lines) It tests the store's checkout process, What it does is roughly following: grab product info add_to_cart add purchaser information (phone, name, address etc) (extra) add coupons or points to use create an order from cart handle payment (bypassing actual payment gateway, but still need to do something like stock decreasing, change order status etc) cancel the order (because created order data needs to be reused, I'm putting them together) How to break up pytest tests when many objects need to be shared.. - 
        
Function instead of class django
I am wondering how to write it, but in function instead of class? from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' - 
        
How to figure out NoReverseMatch at / in Django
Hi and thank you for your time Im using Django and i've got a following issues: NoReverseMatch at /dashboard/. NoReverseMatch at /event/. When i try to go to the dashboard page or to the event_list page i get the error. I know that it depends to url's links put in the templates files that use EventoDetailView and url name=dettagli but i don't understand the reason why. Im trying to figure it out but im not be able to do this. This is the code: Model.py class Evento(models.Model): nome = models.CharField(max_length=200, default='', blank=True, null=True) descrizione = models.TextField(max_length=5000, default='', blank=True, null=True) slug = models.SlugField() objects = models.Manager() cover = models.ImageField(upload_to='media/', default='', blank=True, null=True) data = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) author = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Balneatore", null=True) stabilimento = models.ForeignKey(Stabilimento, blank=True, null=True) saved = models.ManyToManyField(User, related_name='saved', blank=True) def __unicode__(self): return self.nome def total_saved(self): return self.saved.count() def get_absolute_url(self): return reverse("eventi:dettagli", args=[self.id]) class Meta: verbose_name = "Evento" verbose_name_plural = "Eventi" @receiver(pre_save, sender=Evento) def pre_save_slug(sender, **kwargs): print (kwargs) slug = slugify(kwargs['instance'].nome) kwargs['instance'].slug = slug View.py def EventiListView(request): evento_list = Evento.objects.all() evento_filter = EventoFilter(request.GET, queryset=evento_list) context = { 'evento_list': evento_list, } return render(request, 'evento_filter_list.html', {'filter': evento_filter}, context) def EventoDetailView(request, id): evento = get_object_or_404(Evento, id=id) #eventi_salvati = Evento.objects.filter(saved=saved) is_saved … - 
        
How do I make and access regex capture groups in Django without RawSQL?
How do I annotate a Django queryset with a Regex capture group without using RawSQL so that I later can use that value for filtering and sorting? For example, in PostgreSQL I could make the following query: CREATE TABLE foo (id varchar(100)); INSERT INTO foo (id) VALUES ('disk1'), ('disk10'), ('disk2'); SELECT "foo"."id", CAST((regexp_matches("foo"."id", '^(.*\D)([0-9]*)$'))[2] AS integer) as grp2 FROM "foo" ORDER BY "grp2" dbfiddle - 
        
Jquery POST in Django (continued)
I have read the 2 posts related to this subject. Can't make them apply to my case: I get a word that I pick from a radio button. I send that word via jquery ajax POST to a view function. That word should serve the purpose of filtering the query set like the WHERE in a sql query. Then the other issue is how I can get the proper content so that I can write it in the html template. I got that when I was not using jquery but now that I do, don't know how to use what I get from the view function. JQUERY $(document).ready(function(){ $('input[type="radio"]').click(function(){ var valor = $(this).val(); $.post('home', {valor:valor}, function(data)) $('#feedback').text(data); // this won't help. I actually need something like what I get with return //render(request, 'home.html', {'listoflanguages': listoflanguages}) }); }); VIEW FUNCTION def home(request): valor = request.POST.get('valor') listoflanguages = Language.objects.values('language','lesson', 'description', 'url').order_by('language', 'lesson').annotate(count=Count('lesson')) listoflanguages = listoflanguages.filter(valor) # I want to filter it here WHERE... return render(request, 'home.html', {'listoflanguages': listoflanguages}) AND THE TEMPLATE {% for item in listoflanguages %} <tr> <td class="align-middle">{{ item.language }}</td> // how can I implement what I get from the view? etc etc - 
        
Django 2.2.x returns on specific computer: The requested resource was not found on this server
I have the same code running under Django 2.2.1 (also tried 2.2.5). Serving the page with python manage.py runserver The login page and also admin page is served. But after login there is a redirect to another page example.com/worklist which is not working on one computer. On the other system the page is served. On the first computer django returns: Using the URLconf defined in ms_worklist.urls, Django tried these URL patterns, in this order: admin/ accounts/ logout worklist/ The current path, worklist, didn't match any of these. The code is identical on both computers: The main app: # ms_worklist/urls.py from django.contrib import admin from django.urls import path, include admin.site.site_header = 'Worklist Admin' urlpatterns = [ path('', include('pages.urls')), path('worklist/', include('worklists.urls')) , path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')) ] And the worklist app: # worklists/urls.py from django.urls import path from django.db.utils import OperationalError from worklists.views import upload_csv, load_methods urlpatterns = [ path('', upload_csv, name='worklist'), path('ajax/load-methods/', load_methods, name='ajax_load_methods') ] - 
        
How Not Duplicate Submit Form - without JavaScript - DJango
The objective of this is create an input where the user introduce username, there are 2 buttons that submit the form with OK or NO. The problem is that when I submit the form everything is going well but when 'reload' button is pressed the form is sent it again and the username is written in the database. How can I avoid this? Just submit the form, save the username in database, and then show the success message Preventing POST on reloading a form? This is the code: view.py def notificationchecker(request): user = '' # comprobamos cookie de usr try: user = request.COOKIES['user'] except Exception as e: print("Not cookie found: " + str(e)) finally: if user is not '': form = CheckerForm(initial={'user': user}) else: form = CheckerForm() # comprobamos cookie de success notification try: success = request.COOKIES['success'] date = request.COOKIES['date'] response = render( request, 'notificationchecker/notificationchecker.html', {'form': form, 'success': success, 'date': date, 'user': user} ) response.delete_cookie('success') response.delete_cookie('date') return response except Exception as e: print("Not cookie found: " + str(e)) return render( request, 'notificationchecker/notificationchecker.html', {'form': form, } ) def notificationchecker_result(request): form = CheckerForm(request.POST) if request.method == "POST": if form.is_valid(): ntchecker = form.save(commit=False) ntchecker.device = request.user_agent.ua_string ntchecker.option_selected = request.POST['option_selected'].lower() date = timezone.now() ntchecker.checked_date … - 
        
Django - Form (populate field with instance)
obj = Contact.objects.get(id=1) return is -> 124571 myName from my database instanceForm = ContactFormDjango(request.POST or None, instance=obj) ContactFormDjango was a form field with contact and name my question is, how can i use my obj(Contact object id=1) to populate my form field as initial value when its load. - 
        
When to use form methods
I am reading the Django documentation and ran across a couple examples in the forms sections that I do not understand why they did something 2 separate ways.. In the first example I found they send email from the FBV. This makes a lot of sense to a beginner. from django.core.mail import send_mail if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = ['info@example.com'] if cc_myself: recipients.append(sender) send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/thanks/') In the second example I found they use CBVs and apply methods to the form and call this method in the view: from django import forms class ContactForm(forms.Form): name = forms.CharField() message = forms.CharField(widget=forms.Textarea) def send_email(self): # send email using the self.cleaned_data dictionary pass from myapp.forms import ContactForm from django.views.generic.edit import FormView class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/thanks/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) When should you apply form methods and call those methods in the view? Is there a benefit to writing the code this way? Also, in the second example they used pass in the send_email() … - 
        
Add an Image field and audio field on the front end. Using Django backend and reactjs front end
I need to add an image field and audio field in the front end.The Audio file should be accepted from a user in the front end. Then, machine learning file should be given the accepted file for processing and a text and image returned from it should be shown in the front end. How can I proceed? - 
        
Django - Bad request syntax or unsupported method
I want to post data via an api onto my django app. This is how far I got: import pandas import requests excel_data_df = pandas.read_excel('workorders.xlsx') json_str = excel_data_df.to_json(orient='records', date_format='iso') API_ENDPOINT = "http://127.0.0.1:8000/api/create/" API_KEY = "dF8NbXRA.94Mj2xeXT3NZOtx1b575CvNvbs8JWo0D" source_code = json_str data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'csv'} r = requests.post(url = API_ENDPOINT, data = data) apitest = r.text views.py class PostDataView(CreateAPIView): queryset = Workorder.objects.all() serializer_class = WorkorderSerializer serializers.py class WorkorderSerializer(serializers.ModelSerializer): class Meta: model = Workorder exclude = ['id'] I can enter the data manually using the post forms @ api/create but when I try to post it via the api, I get this error: <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Error response</title> </head> <body> <h1>Error response</h1> <p>Error code: 400</p> <p>Message: Bad Request.</p> <p>Error code explanation: 400 - Bad request syntax or unsupported method.</p> </body> </html> This is the data I want to post: [{"id":null,"label":"Workorder 1","start":"2019-01-01T00:00:00.000Z","end":"2019-01-10T00:00:00.000Z","duration":9,"ctype":"bar","werk":"a","product":"a","train_number":535435.0,"latest_start_date":"2019-01-10T00:00:00.000Z","latest_start_timebucket":9,"is_start_date_fixed":false,"assigned_start_timebucket":535435.0,"assigned_start_date":"2019-01-10T00:00:00.000Z","costs_early_start":334,"costs_late_start":334,"resource_overall_demands":334,"resource_timeslots_demands":334}, {"id":null,"label":"Workorder 2","start":"2019-01-02T00:00:00.000Z","end":"2019-01-06T00:00:00.000Z","duration":4,"ctype":"bar","werk":"b","product":"b","train_number":234234.0,"latest_start_date":"2019-01-06T00:00:00.000Z","latest_start_timebucket":4,"is_start_date_fixed":false,"assigned_start_timebucket":234234.0,"assigned_start_date":"2019-01-06T00:00:00.000Z","costs_early_start":344,"costs_late_start":344,"resource_overall_demands":344,"resource_timeslots_demands":344}] I think its because of the T00:00:00.000Z, as Im using only Datefields. Is there any way to remove the time from the date? Thank you for any help - 
        
Connect two Django apps with same initial workflow
I have a django project whereby the initial workings of two apps is essentially the same. Therefore, I have split the initial workings (a couple of forms) into its own init application. The idea is then to continue the workflow in the application in one of the two apps (app1 or app2). The idea is to connect the success_url of the last FormView in the init app to the index url of the app to use. I have thought about using sessions to store the url from app1 and redirect to the init app but this has its own implications due to the use of sessions, ie expiry etc. How else could the 'bridge' be performed? - 
        
How to install python 'secrets' for Django on Ubuntu 16.04?
When trying to run python3 manage.py makemigrations on an Ubuntu 16.04 Digital Ocean droplet, I get this error: ImportError: No module named 'secrets' I'm not getting that error on localhost. When I looked up 'secrets' I looks like its a standard library in Python 3.6 and later releases. Is there something I could've done that would remove it, and how can I get it back? - 
        
Django M2M field in a Model Form?
I have a many to many field ConnectedTo in my model and I want to create the object using a form. However when I list it as a field I just get a box with options to highlight and no way of selecting one or more. Ideally I'd love a multiple selection checkbox with a list of items in a scroll box. But I'd start with just having a selectable item. Here's my code so far: models.py: class Part(models.Model): PartID = models.AutoField(primary_key=True, unique=True) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True) Comment = models.CharField(max_length=255, blank=True) Subtype = models.ForeignKey('Subtype', on_delete=models.CASCADE, null=True) Location = models.CharField(max_length=255, blank=True) ConnectedTo= models.ManyToManyField('self', blank=True, null=True) BatchNo = models.CharField(max_length=32, blank=False, null=True) SerialNo = models.CharField(max_length=32,blank=True) Manufacturer = models.CharField(max_length=32, blank=False, null=True) Length = models.CharField(max_length=6, blank=True, null=True) InspectionPeriod = models.IntegerField(blank=True, null=True) LastInspected = models.DateField(blank=True, null=True) InspectionDue = models.CharField(max_length=255, blank=True) @classmethod def create(cls, siteid, comment, subtype, location, batchno, serialno, manufacturer, length, inspectionperiod, lastinspected, inspectiondue): part = cls(SiteID = siteid, Comment = comment, Subtype = subtype, Location = location, BatchNo = batchno, SerialNo = serialno, Manufacturer = manufacturer, Length = length, InspectionPeriod = inspectionperiod, LastInspected = lastinspected, InspectionDue = inspectiondue) return part def __str__(self): return str(self.PartID) forms.py: class PartForm(forms.ModelForm): class Meta: model = Part fields = … - 
        
Remove From cart Button not working in django?
When i try to remove item from my cart, remove from cart button accessing add-to-cart definition and when i click on remove button, it increase item in the cart means both add-to-cart and remove-from-cart perform same functionality. here, my views.py from django.shortcuts import render, get_object_or_404, redirect from products.models import Product from order.models import Order, OrderItem from django.utils import timezone def cart(request): return render(request,'order/cart.html') def add_to_cart(request,product_id): item = get_object_or_404(Product, pk=product_id) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user = request.user, ordered = False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if order.items.filter(item__id = item.id).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user = request.user, ordered_date = ordered_date) order.items.add(order_item) return redirect("/products/"+ str(product_id)) def remove_from_cart(request,product_id): item = get_object_or_404(Product, pk=product_id) order_qs = Order.objects.filter(user = request.user, ordered = False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if order.items.filter(item__id = item.id).exists(): order_item= OrderItem.objects.filter( item=item, user=request.user, ordered=False )[0] order.items.clear(order_item) else: #add a message that user does not contain order item return redirect("/products/"+ str(product_id)) else: #add a message that user does not have an order return redirect("/products/"+ str(product_id)) return redirect("/products/"+ str(product_id)) urls.py from django.urls import path … - 
        
Django query - How to get concurrent number of records in 5 minutes span of time?
I'm very new in Django and Sql. Sorry for this basic question. I have below model with Django + PostgreSql to record activity start/stop time; class Test(models.Model): class Meta: unique_together = ('test_session_id',) test_session_id = models.CharField(max_length=100, default=None, null=True) started_at = models.DateTimeField(auto_now_add=False, blank=True, null=True) finished_at = models.DateTimeField(auto_now_add=False, blank=True, null=True) I want to figure out how many tests is running in every 5 minutes span of time. If below four session exists, could you please guide me how to write Django queryset to achive below result? Sample Data ==== Test#1 11:33 ~ 12:17 Test#2 11:44 ~ 12:51 Test#3 12:08 ~ 12:19 Test#4 12:21 ~ 12:55 Expected query result === 11:30 => 0 11:35 => 1 11:40 => 1 11:45 => 2 ... 12:10 => 3 12:15 => 3 12:20 => 1 12:25 => 2 ... - 
        
In my Django portal after login to the portal my request.user is always giving the value AnonymousUser
def login(request): if request.method == 'POST': form = AuthForm(request.POST) if form.is_valid(): userEmail = strip_html(form.cleaned_data['auth_email']) userPassword = strip_html(form.cleaned_data['auth_password']) try: person = Auth.objects.get(auth_email=userEmail, auth_password=userPassword) request.session['username'] = person.auth_name return redirect("/crudapplication/show") except: page = 'login.html' message = 'Username doesn\'t exist' Above is a small code snipet. This is my login functionality.So the value of the user email and password I'm providing is present in my database. So when I'm printing the line on console by print(request.user) it always gives the value Anonymoususer. The login function is the part of views.py of my login module - 
        
Accessing dictionaries in Django templates
views.py: return render(request,'images.html',temp) Temp: {'cluster1': ['temp/vinoth/cluster1/demo-pic94.jpg', 'temp/vinoth/cluster1/id1.jpg'], 'cluster2': ['temp/vinoth/cluster2/demo-pic94.jpg', 'temp/vinoth/cluster2/demo-pic99.jpg', 'temp/vinoth/cluster2/id2.jpg', ['temp/vinoth/cluster2/demo-pic94.jpg', 'temp/vinoth/cluster2/demo-pic99.jpg', 'temp/vinoth/cluster2/id2.jpg']], 'cluster3': ['temp/vinoth/cluster3/demo-pic96.jpg', 'temp/vinoth/cluster3/id3.jpg'], 'cluster4': ['temp/vinoth/cluster4/demo-pic99.jpg', 'temp/vinoth/cluster4/id4.jpg'], 'cluster5': ['temp/vinoth/cluster5/demo-pic99.jpg', 'temp/vinoth/cluster5/id5.jpg'], 'cluster6': ['temp/vinoth/cluster6/id6.jpg', 'temp/vinoth/cluster6/triplet loss.jpg'], 'cluster7': ['temp/vinoth/cluster7/id7.jpg', 'temp/vinoth/cluster7/triplet loss.jpg'], 'cluster8': ['temp/vinoth/cluster8/id8.jpg', 'temp/vinoth/cluster8/triplet loss.jpg'], 'cluster9': ['temp/vinoth/cluster9/id9.jpg', 'temp/vinoth/cluster9/triplet loss.jpg']} System check identified no issues (0 silenced). The Values are array of images image.html: <div class="row mt-4"> <div class="col"> <ul class="list-group"> {% for key,value in temp.items %} <h1>{{ key }}</h1> {% endfor %} </ul> </div> </div> But nothing gets printed What am i doing wrong here? - 
        
How can I properly catch errors of a Node js script in Python using Naked?
I am using Naked library of Python mentioned here for executing a Nodejs script which is also available here too. The point is, whenever I run my python script(exactly taken from the above link) through the terminal I can able to see the output of the nodejs script. I included this python script into my Django server and running it whenever an API call is made. I couldn't able to catch the errors properly when the validation of the page fails. It always returns 'success'. I feel this is because Nodejs is asynchronous. If it is so, how can I make the function 'amphtmlValidator.getInstance().then(function(validator)' mentioned in the npm website to synchronous? I am really very much new to Nodejs. Actually I just need to validate AMP pages from python script in Django and the only way I found is calling the node script through python. Everything is ok, but I couldn't catch the errors properly. Please help.