Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does python manage.py runserver not work?
The command python manage.py runserver does not work when postgressql is the backend. There is no problem with the default sqllite I tried with keeping my project both in the c and d drive but in both places I get the same error when I use postgressql as the backend. I have also ensure that the postgres server is on and not shut off. In the django settings file this is the code DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydatabase', 'USER': 'postgres', 'PASSWORD': 'abc123', 'HOST': '127.0.0.1', 'PORT': '5432', } } the last 2-3 lines of the error in the command prompt are django.db.backends.postgressql isn't an available database backend. Try using mysql, oracle, sqllite3. -
What Does Django static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Actually DO?
I am using Django 2.2. From the Django Managing static files documentation: If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True. If you don’t have django.contrib.staticfiles in INSTALLED_APPS, you can still manually serve static files using the django.views.static.serve() view. This is not suitable for production use! For some common deployment strategies, see Deploying static files. For example, if your STATIC_URL is defined as /static/, you can do this by adding the following snippet to your urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Note This helper function works only in debug mode and only if the given prefix is local (e.g. /static/) and not a URL (e.g. http://static.example.com/). Also this helper function only serves the actual STATIC_ROOT folder; it doesn’t perform static files discovery like django.contrib.staticfiles. My Interpretation static is a helper function that serves files from the STATIC_ROOT during development (is this True?) static only works when debug = True static only works with a local prefix like STATIC_URL = '/static/' When DEBUG is set to True and I use and setup … -
How to fix 'AttributeError: 'Person' object has no attribute '_default_manager' in Django is_valid() method
I'm using django rest and I'm trying to update my django model with the changed values from a form POST.I place the model to be updated and new data in the serializer instance. model_serializer = serializer.PersonSerializer(queryset, request.POST) When performing model_serializer.is_valid() I get the error AttributeError: 'Person' object has no attribute '_default_manager' I've looked at similar questions to this. I haven't found anything regarding a model object not having a '_default_manager' In these questions they suggest changing the name of method/model due to conflicts. This hasn't worked for me. class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class PersonSerializer(serializers.ModelSerializer): class Meta: model = models.Person() fields = '__all__' url(r'^api/personview/', views.PersonView.as_view()), class PersonView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'rest_person_form.html' def get(self, request): queryset = models.Person.objects.all().last() model_serializer = serializer.PersonSerializer(queryset) return Response({'serializer': model_serializer, 'queryset': queryset}) def post(self, request): queryset = models.Person.objects.all().last() model_serializer = serializer.PersonSerializer(queryset, request.POST) model_serializer.is_valid() model_serializer.save() return Response({'serializer':model_serializer}) I'm expecting the is_valid() method to pass without errors to allow me to save my updated details into my model. -
template tag to remove dot dot dot when using truncate
I have a code that displays string "season #" +"seriesname" I want to display season # only thus I thought about using truncate filter {{ each_season.season_nr|truncatechars:9 }} But with this approach I get season 1... I think I have to use a template tag for this. or is there a simpler way? i'm not sure how to write the code for the template tag. any help would be appreciated -
how to dynamically change dropdown menu in html from django template
I create a dictionary in django views.py like this: tmp={"K1":['V1','V2'],"K2":['V3','V4']} and in my html page,I create two dropdown menu. menu D1 can select key from dictionary (K1/K2) in html: <select name="D1"> {% for key, value in tmp.items %} <option value="{{key}}">{{key}}</option> {% endfor %} </select> now I want create menu D2 dynamically change with D1 select,for example, if I select K1 in D1,dropdown menu D2 will show V1 V2 and when I change to K2 in D1,menu D2 will show V3 V4,I suddenly don't know how to do it,can any one help me? very thanks! -
How to change default python version from python v2.7 to python 3.7?
I have installed Linux system on AWS. And I am trying to develop python django app on it. I noticed that the default python version is 2.7 but I do need python v3.7. So I installed python 3.7 package. But when I run this command "which python", I can get "/usr/bin/python" and "python -V" again, I can get python 2.7.16. And when I run this command "which python3.7", I can get "/usr/local/bin/python3.7" and "python3.7 -V" again, I can get python 3.7. So I used alias command to change the default version, but it didn't work when I logout and login again. So I just want to know how to change the default version in AWS linux. Thanks -
How to integrate voice search in e-commerce website (for searching products)?
I want to integrate voice search in e-commerce website to help customers find products by voice. Then I use that voice to analyse their emotion. But I am not sure about the way to collect their voice by building voice search in e-commerce website. -
How to Reference Model in Reportlab
My goal is to create a pdf report using ReportLab where some of the text is dynamic based on a primary key. I have a dropdown listing each primary key currently created in the program (#1 - 5 at present) and as more "shipments" are created, the primary key is added to the dropdown. When I select the primary key and then click the "submit" button I would like for my pdf to generate where the dynamic text is related specifically to that pk. Below is the view for the PDF I currently have with static text (pulled from a source on reportlab) where I would like values such as "JOHN DOE" and "Name goes here" to be replaced dynamically based on the pk selected. views.py def write_pdf_view(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) # Start writing the PDF here p.setLineWidth(.3) p.setFont('Helvetica', 12) p.drawString(30,750,'Name goes here') p.drawString(30,735,'OF ACME INDUSTRIES') p.drawString(500,750,"12/12/2010") p.line(480,747,580,747) p.drawString(275,725,'AMOUNT OWED:') p.drawString(500,725,"$1,000.00") p.line(378,723,580,723) p.drawString(30,703,'RECEIVED BY:') p.line(120,700,580,700) p.drawString(120,703,"JOHN DOE") # End writing p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response I am presently completely unsure how to approach this problem. I have the dropdown and I understand how to create a … -
django inlineformset save new parent and child
The goal is to create a webpage that allows people to take pictures and submit meta data about the pictures. Because there can be multiple pictures for the same meta data I've setup the models like so: models.py import uuid from django.db import models from project.settings import AUTH_USER_MODEL class MetaData(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_id = models.ForeignKey( AUTH_USER_MODEL, null=True, blank=True, to_field='id', on_delete=models.DO_NOTHING, related_name='' ) description = models.CharField(max_length=5000) class Image(models.Model): image = models.ImageField() metadata_id = models.ForeignKey( MetaData, on_delete=models.DO_NOTHING, related_name='image_to_metadata' ) With the models simple forms were created: forms.py from django.forms import ModelForm from django.forms.models import inlineformset_factory from .models import MetaData, Image class MetaDataForm(ModelForm): class Meta: model = MetaData fields = '__all__' class Image(ModelForm): class Meta: model = Image fields = '__all__' MetaDataImageFormSet = inlineformset_factory(MetaData, Image, form=MetaDataForm, fields=('image',)) then using the following view to display them and authentication based on the following guide Django inline formsets with class based views views.py from django.views.generic import CreateView from django.db import transaction from .forms import MetaDataForm, ImageForm, MetaDataImageFormSet from .models import MetaData class CaptureView(CreateView): model = MetaData template_name = 'pages/capture.html' form_class = MetaDataForm success_url = "/" def get_context_data(self, **kwargs): data = super(CaptureView, self).get_context_data(**kwargs) if self.request.POST: data['images'] = MetaDataImageFormSet(self.request.POST, self.request.FILES) else: data['images'] = MetaDataImageFormSet() return … -
how to only show number with truncate or css
I want to display S1 only instead of season 1. Thus I need to truncate season and put only 1 and add "S" at the front. <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season}} </a> how do I truncate the word "season"? -
why I have issues in importing views in the urls.py file?
from employee import views does not work!...the server is giving a page not found (404) response I feel like the urls can't access my views this is the views.py from .models import Employee # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.all() return render(request,"show.html",{'employees':employees}) def edit(request, id): employee = Employee.objects.get(id=id) return render(request,'edit.html', {'employee':employee}) def update(request, id): employee = Employee.objects.get(id=id) form = EmployeeForm(request.POST, instance = employee) if form.is_valid(): form.save() return redirect("/show") from django.contrib import admin from django.urls import path from employee import views urlpatterns = [ path('admin/', admin.site.urls), path('emp', views.emp), path('show',views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] urls.py I am having unresolved import 'employee'message -
Overlay (Modal) Windows in Django
What is the best way to open an overlay window (not necessarily a modal) in Django? My process is such that I generate a heatmap using D3.js and when a user clicks on a cell in the heatmap, an Ajax call is made to a Django view and that view is responsible for creating the visualization of a waveform that should be superimposed on top of the heatmap. I've looked at django-popup-view-field and bootstrap modal forms but they are designed to work with forms. Can they used independently of Django forms? What other alternatives are available? Any help would be greatly appreciated. Thanks. -
Insert scrapped data into the database
I am trying to write a scrape script that will return the following information: 10 most common words with their number and The 10 most common words with their numbers per author (all later available as django rest api) I have two issues - insert scraped data into the pgsql database and I'm not sure about the loops that return "authors" and "post content" I try to insert scraped data into the pgsql database but the data doesn't go into the database. import requests from bs4 import BeautifulSoup as bs from selenium import webdriver import psycopg2 as pg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept' : 'text/html,application/xhtml+xml, application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page- number').text.split('/'[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome() for article in all_links: d.get(article) soup = bs(d.page_source, 'lxml') [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])] visible_text = soup.getText() … -
Sorl-thumbnail not generating thumbnails in '/cache' folder
I am trying to use sorl-thumbnail in my templates but I have been unable to successfully generate the thumbnails in the proper '/cache' directory that 'sorl-thumbnail' uses to retrieve thumbnails. It seems that this problem has happened to a number of people before, however previous solutions have not worked for me. I have run ./manage.py migrate and I have ensured that I am using the sorl.thumbnail.ImageField rather than the default django.db.models.ImageField in my models.py and I have tried using ./manage.py thumbnail cleanup and ./manage.py thumbnail clear. I have also read that memcached could be interfering with things, but even with all mentions of memcached commented out, I can't get sorl-thumbnails to work. For reference, I am running my project on an Ubuntu 18.04.2 apache2 server hosted by DigitalOcean. html: {% for obj in object_list %} ... {% thumbnail obj.image "75x75" as im %} <img class = "artwork" src="{{im.url }}"/> {% endthumbnail %} ... {% endfor %} settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sorl.thumbnail', 'posts', 'login', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "/home/arthouse/workspace/code/side_proj/assets/") ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "/home/arthouse/workspace/code/side_proj/static_cdn/") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "/media_cdn") models.py: from sorl.thumbnail import ImageField class Post(models.Model): image = … -
Unable to call objects methods in django ''function' object has no attribute 'objects'"
Im trying to display some objects from django. When I use the administrator my objects are created but when I try to display it is impossible. I tryed to make a render but when I initialize the screen never is called, then i tryed to make it with a GET button, now the function is called but when arrives to alumnos = Alumno.objects.all() throws 'function' object has no attribute 'objects'. models.py class Alumno(models.Model): dni = models.CharField(max_length=9,primary_key=True) nombre = models.CharField(max_length=100) apellido1 = models.CharField('Primer apellido',max_length=50) apellido2 = models.CharField('Segundo apellido',max_length=50) email = models.EmailField("Correo electronico",null=True) repetidor = models.BooleanField() curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos") Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel')) Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica')) Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso')) objects = models.Manager() def __str__(self): return self.dni class Meta: db_table = "Alumno" verbose_name = 'Alumno' verbose_name_plural = 'Alumnos' unique_together = ("nombre", "apellido1", "apellido2") view.py def mostrar_alumnos(request): alumnos = Alumno.objects.all() context = {'Alumno': alumnos} return render(request, "mostrar_alumnos.html", context) mostrar_alumnos.html {% if mostrar_alumnos %} <ul> {% for alumno in mostrar_alumnos %} <td>{{ Alumno.dni }}</td> <td>{{ Alumno.nombre }}</td> <td>{{ Alumno.apellido1 }}</td> <td> <a class="btn btn-secondary" href="{% url 'actualizar_alumno' alumno.dni %}"> Editar</a> <a class="btn btn-danger" href="{% url 'eliminar_alumno' alumno.dni %}"> Esborrar</a> </td> {% endfor %} </ul> {% else … -
how to do query that validates 2 values from the source table in django
Do query target table which must validate 2 values from the source table SELECT ID_MAQ, NOM_EMP, DES_MOD, DES_JGO, DES_MAR FROM M_MAQ INNER JOIN M_EMP ON M_MAQ.ID_EMP = M_EMP.ID_EMP INNER JOIN A_MOD ON M_MAQ.ID_MOD = A_MOD.ID_MOD AND M_MAQ.ID_MAR = A_MOD.ID_MAR INNER JOIN A_JGO ON M_MAQ.ID_JGO = A_JGO.ID_JGO AND M_MAQ.ID_MAR = A_JGO.ID_MAR AND M_MAQ.ID_MOD = A_JGO.ID_MOD INNER JOIN M_MAR ON M_MAQ.ID_MAR = M_MAR.ID_MAR ORDER BY ID_MAQ ASC I have that SQL query, how could I do it using django ORM? I tried with select_related but not get the correct value, since the query "ON M_MAQ.ID_MOD = A_MOD.ID_MOD AND M_MAQ.ID_MAR = A_MOD.ID_MAR" needs to evaluate from table M_MAQ with that of M_MOD the ID_MOD and ID_MAR. someone knows how he could do it? -
URL routing in Django
i am prrety new in URLs and Django and got some questions For now I have 2 HTML templates which are routing correctly: home.html and ladder.html . What do I have to do to go from my ladder.html(ladder/) back to my home.html("") if I click to home again nothing is happening. And as second when I am on ladder and click ladder again it adds another ladder/ to the URL and Im getting a router error , how can I resolve this ? Thanks for the help. I will show the code of my navbar wher my href attributes are so u can understand what I mean and my urls.py My hrefs: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="ladder/">Ladders</a> My urls.py: from django.contrib import admin from django.urls import path from pages.views import home_view,ladder_view from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', home_view), path('admin/', admin.site.urls), path('ladder/',ladder_view), ] -
Why using Gunicorn with GEvent could increate the query time to Redis/Database?
In actual production load (web app) with an Redis server (v4.x) when using gunicorn with worker_class gevent the query time increases by 3. Database access also got worse (but not so much, only 50%). I'm trying to figure out why this would happen. Any ideas? The app is very IO Bound, with lots of database queries and redis accesses for every single request, which should be the perfect scenario for gevent. Moving from SYNC to GEVENT (~11 A.M) Would the monkey patching to the socket decrease performance somehow? I tried to fine tuning worker_connections without success, even the extremely low level of just 2 (almost sync again), give me the same bad results. Am I missing some gotcha for how gevent and it's pseudothreads work? Disclaimer: I'm using NewRelic to monitor the performance and redis-py/django/mysql. I tried some tweaks like using the BlockingConnectionPool for Redis, but my Database access performance also decreased so Redis is not the only problem. The worker size is 5 (CPUs * 2 + 1). I also had tons of GreenletExit/ConnectionError[redis] at random times, which was minimized by moving worker_connections from 2k (default) to 10. -
how to run a python file on a django website
I (a django beginner) am making a website (http://tijmenmeijer.pythonanywhere.com/articles/) with django. I created a python file and I'd like to run that file on my website.. how to do that? import requests import pygame,sys pygame.init() run = True while run: headers = {'Referer' : 'https://www.windguru.cz/station/219'} r = requests.get(' https://www.windguru.cz/int/iapi.php?q=station_data_current&id_station=219&date_format=Y-m-d%20H%3Ai%3As%20T&_mha=f4d18b6c', headers = headers).json() maxwind = r['wind_max'] minwind = r['wind_min'] avgwind = r['wind_avg'] temp = r['temperature'] direction = r['wind_direction'] date = r['datetime'] for event in pygame.event.get(): if event.type == pygame.QUIT: quit() screen = pygame.display.set_mode((300,100)) screen.fill((100,255,255)) sys_font = pygame.font.SysFont("None",23) render = sys_font.render(str(avgwind) + str(' knopen -- ') + str(maxwind) + str(' max -- ') + str(minwind) + str(' min'), 0,(0,0,0)) screen.blit(render, (35,10)) pygame.display.update() -
Can you filter querysets by user in models?
I suppose the proper way to filter objects by user is done in views because you can easily require login and you have access to request.user. But I have a view that invokes the object's classmethod, which can't be combined with a filter because it converts the queryset to a list object- so I'm thinking if there's a way to filter the queryset by user directly in models, then when I invoke the classmethod in views the objects will already be filtered. Here's my view: def leads_by_city(request): # Invoke Lead classmethod to get the data data = Lead.objects.get_leads_per_city() return JsonResponse(data, safe=False) Model with custom Manager: class Lead(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) source = models.ForeignKey(LeadSource, on_delete=models.CASCADE) city = models.CharField(max_length=100) objects = LeadManager() class LeadManager(models.Manager): def get_leads_per_city(self): queryset = self.values('city').annotate(Count('id')).order_by('city') data = list(queryset.values('city', 'id__count')) return data Is there a way to filter by user in the classmethod? Maybe like: class LeadManager(models.Manager): def get_leads_per_city(self,user): queryset = self.filter(user=Lead.user).values('city').annotate(Count('id')).order_by('city') data = list(queryset.values('city', 'id__count')) return data -
Best way to design a dynamic navbar menu with Django?
i will be pleased to see your recommendation of the best way to design the models and views or other thing to make that navbar an advance and responsive one! -
How can I get the model created by super().create() in a ModelViewSet?
I'm trying to get a copy of the model created by super().create() in my ModelViewSet's create() method. What's the simplest way to do that? I have a ModelViewSet that takes a generic POST request, which I know is good because I end up with a new record in my DB. What I want to do is get the object that was just created so I can return its pk to the client. However, the following will not work: class ItemViewSet(viewsets.ModelViewSet): model = Item # ... def create(self, request, *args, **kwargs): super().create(request, *args, **kwargs) # Successfully creates instance instance = self.get_object() # Throws error return Response({'status': 'success', 'pk': instance.pk}) Like with other DRF ModelViewSet methods, I'd expect self.get_object() to get me the instance created, though this is usually only usable in a "detail route". What I get instead is the following error: AssertionError: Expected view CultivarStockViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. Any insight is appreciated! -
How can I paginate get_context_data choosing from among multiple context objects?
I am trying to paginate get_context_data from views.py, by selecting from among multiple context objects. Only two choices are shown in the code example conditional statements, but I have several more choices which basically cover all choices from the form submission. Only one context is returned, in the end however, passing the context to the template view for pagination. I tried also setting pagination globally in settings.py, but it is not working. I have viewed the article below, previously, as a guide to pagination on get-context-objects. How to perform pagination for context object in django? From views.py: from django.shortcuts import render import django.views.generic from django.http import HttpResponse from django.template import loader from django.template import RequestContext from ephemera.models import * from ephemera.serializers import ItemSerializer from rest_framework import generics from ephemera.forms import SearchForm, AdvSearchForm from itertools import chain from django.core.paginator import Paginator from django.core.paginator import EmptyPage from django.core.paginator import PageNotAnInteger class SearchResultsAdvancedView(django.views.generic.ListView): template_name = 'ephemera/searchresults_advanced.html' form = AdvSearchForm() paginate_by = 10 model = Item def get_context_data(self, **kwargs): context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs) choose_collection = self.request.GET.get('choose_collection') user_input = self.request.GET.get('user_input') choose_item = self.request.GET.get('choose_item') bookpage = False imagepage = False if choose_collection == 'All' and user_input == '' and choose_item == 'book': context['book_qs'] = Item.objects.raw('SELECT * … -
Django runserver on Chromebook (Crostini)
I'm using a Chromebook HP 11 G5 EE and try to develop with Django. I use Crostini (Linux terminal into Chrome OS with no developper mode). I've created a virtualenv inside my home directory and installed with pip all my requirements. When I try to do (with source bin/activate) : ./manage.py runserver It returns me : Performing system checks... System check identified no issues (0 silenced). May 28, 2019 - 20:02:11 Django version 2.1.5, using settings 'myproject.settings' Starting development server at http://0.0.0.0:80/ Quit the server with CONTROL-C. Error: You don't have permission to access that port. I'd try to set parameters like 0.0.0.0:8000, penguin.linux.test:8000, to change ports, I've got the same error. Is someone had the same issue and fixed it ? Thanks ! -
Django Project - bootstrap navigation with javascript script not working - Where should JavaScript go?
I have a Django project, in which I have a simple front-end bootstrap horizontal navigation bar (taken from here: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_ref_js_tab_js&stacked=h). In it, a user clicks on a tab, and it displays the information for that tab, on click. In this case, I have used django templating language and crispy forms to generate a form inside tab 1. This renders fine, and looks correct in terms of formatting and layout, but, the tabs are not functional. I have looked at other stackoverflow questions, but none are specific to what I am asking. The functionality of the tabs, I assume, is controlled by the Javascript code snippet: <script> $(document).ready(function(){ $(".nav-tabs a").click(function(){ $(this).tab('show'); }); }); </script> As a newbie to Django and front-end design, I am struggling to see, a) where I have made the mistake and what needs to be corrected in order for the tabs to function correctly on-click. b) how javascript is implemented inside of the whole structure of a Django html template. By this,I mean, Javascript is usually put inside the 'head' tags, but in this case templates extend a base template in which there is a head, so I am unsure of where Javascript should go. Should I …