Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to get a value from a query set which have kay value pair in database
I have a models.py like class SiteSettings(TimeStampedModel): property_key = models.CharField(max_length=200) property_value = models.CharField(max_length=255) In my views.py the code is like settings = SiteSettings.objects.filter(status=1) how can I display the value of the setting in HTML file. Like in my table has 2 values are property_key property_key is_active site_title Some title 1 site_desc Description of the site 1 Now need to display these 2 values in the template. Thanks, in advance. -
how set different sizes to different products
I want to add different sizes for some products. this method, which I have tried has failed to update sizes in add_to_cart view this costs me a lot so please suggest me a way to update or any new way please help me through this or suggest any other method. thank you in advance. regards Bhavasagar. views.py @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) if request.method == "POST": if len(request.POST.get('sizes_choice')) > 0: order_item.selcsize = order_item.selcsize+str(request.POST.get('sizes_choice')) order_item.save() messages.info(request, "This item is selected with size "+order_item.selcsize) 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__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() #if order_item.selcsize != 'False': if len(request.POST.get('sizes_choice')) > 0: order_item.selcsize = order_item.selcsize+str(request.POST.get('sizes_choice')) order_item.save() messages.info(request, "This item is selected with size "+order_item.selcsize) messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") index.html {% if object.has_size %} <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalPopovers"> select sizes </button> <form method="POST" action="core:add-to-cart" … -
Django dynamic formset
Here's the way I'm doing it: HTML Code <form> <label for="">Invoice No</label> <input type="text"> <label for="">Invoice Date</label> <input type="date"> <table border="1" id="items"> <tr> <th>Item Name</th> <th>Qty</th> <th>Rate</th> </tr> <tr> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text" id="rate"></td> </tr> </table> <input type="submit"> </form> JS Code function createNewRow(){ var table = document.getElementById("items"); var row = table.insertRow(-1); for(i=0; i<3; i++){ var cell = row.insertCell(-1); var el = document.createElement("input"); el.setAttribute("type", "text"); cell.appendChild(el) } } $(document).on('keypress', function(e) { if(e.which == 13 ){ e.preventDefault(); if(e.target.id == "rate"){ var table = document.getElementById("items"); createNewRow(); $("#rate").removeAttr("id"); let lastRow = table.rows[table.rows.length-1]; let lastCell = lastRow.cells[lastRow.cells.length-1]; $(lastCell.firstElementChild).attr("id","rate"); } } }); Models.py from django.db import models # Create your models here. class Purchase(models.Model): invoice_no = models.CharField(max_length=255, primary_key=True) invoice_date = models.DateField() def __str__(self): return '%s' % (self.invoice_no) class Items(models.Model): invoice_no = models.ForeignKey(Purchase, on_delete=models.CASCADE) item_name = models.CharField(max_length=255) qty = models.IntegerField(default=0) rate = models.FloatField(default=0) def __str__(self): return '%s' % (self.item_name) Requirement: Requirement What I want is for a particular invoice number I want to add details of purchase of multiple items and save it in db on submit. I tried using formset but I don't know where I went wrong views.py from django.shortcuts import render from .models import Items from .models import Purchase from django.forms import … -
How to render html with django?
Hi i am practicing Django and Python And i encounter with parse HTML problem, i saved some html through admin page, and i tried to render,but it rendered as string! This is my part of template {% block content %} <div class="article-detail"> <div class="article"> <img src="{{ article.thumb.url }}" /> <h2>{{ article.title }}</h2> <p>{{ article.date }}</p> <div> </div> </div> </div> {% endblock %} And this is my model class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() description = HTMLField('Content', blank=True) body = models.TextField() date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField(default='default.png', blank=True) ... I tried to use javascript {% block content %} <div class="article-detail"> <div class="article"> <img src="{{ article.thumb.url }}" /> <h2>{{ article.title }}</h2> <p>{{ article.date }}</p> </div> </div> <script> var article = "<div>{{ article.description }}</div>" console.log(article); document.write(article); </script> {% endblock %} I hoped this work but But i got syntax Error Why? If it transformed to string, it should work.... And i am sorry for my poor English 😂 -
How to implement web push notification by using Django
I am working on a project where back-end is implemented in django, and i have to implement push notification for web. I didn't do that before. I need a guideline or overview for that, can anyone suggest any good documentation regarding this? -
Unable to read dictionary values in Django template
I have a dictionary that I pass to Django template. If I render just a dictionary with {{dict}} , then it is rendered fine, like this: If I render just the keys with {{appoint}}, they are also rendered just fine, like this: But if I render dictionary values with {{dict.appoint}} then I get nothing I have read every post here about Django, template language and dictionaries and have not been able to solve this seemingly simple problem. -
How to add meta properties each page in django?
Need help How to add meta properties each pages in django ? I have base.html but i need each pages meta tags -
How much money do I need to deploy my project using Django?
This is my first time that I will deploy my project. I have no idea how much money do I need. Also can you guys give me a tip on where I can deploy a website for free with having own domain name? -
How to display data in a drop down corresponding to the data from another dropdown in html page?
I am trying to create a web page using Python DJANGO, in which I have two dropdowns out of which one is for category and another for subcategory, for which data is getting fetched from database. In DB, there are two columns for category and another for subcategory respectively. For example, there are 2 Categories, i.e boys and girls. and for boys there are 3 names under SubCategory column, similarly for girls. So my want is that, in drop down 1, it should show 'boys' and 'girls'. When user chooses any of them, the corresponding names should appear in the second drop down(i.e only boys names should appear in dropdown 2 when "boys" is selected in dropdown1). But the way I have written, its showing all the data irrespective of the selection in dropdown1. Please suggest, how do I make the subcategory data appear categorically? Please find the below sample code, that i have written. View.py: def createTicketView(request): if request.method == 'POST': taskName=request.POST.get('title') taskDescription=request.POST.get('description') Category=request.POST.get('category') SubCategory=request.POST.get('type') user_id=request.user.id task=UserTaskDetails.objects.create(user_id=user_id, taskName=taskName,taskDescription=taskDescription, Category=Category,SubCategory=SubCategory) task.save() return redirect('home') category =ServiceCategoryDetails.objects.values('category').distinct() subcategory=ServiceCategoryDetails.objects.values('SubCategory').distinct() return render(request,'custws/ticket.html',{'title':'create ticket', 'category':category, 'subcategory':subcategory, '}) Html code: <div class="form-group col-md-6"> <label for="category" class="font-weight-bold">Category</label> <select name="category" id="category" class="form-control"> {% for type in category %} … -
django-rest-auth urls not found
I'm trying to implement django-rest-auth, but the url is not recognized and throw 404 error. The 'rest_auth' is added in the INSTALLED_APPS and path also included in the urls.py file. Request URL: http://127.0.0.1:8000/api/v1/rest-auth/login/ Using the URLconf defined in blog_project.urls, Django tried these URL patterns, in this order: admin/ api/v1/ <int:pk>/ api/v1/ api-auth/ api/v1/rest-auth ^password/reset/$ [name='rest_password_reset'] api/v1/rest-auth ^password/reset/confirm/$ [name='rest_password_reset_confirm'] api/v1/rest-auth ^login/$ [name='rest_login'] api/v1/rest-auth ^logout/$ [name='rest_logout'] api/v1/rest-auth ^user/$ [name='rest_user_details'] api/v1/rest-auth ^password/change/$ [name='rest_password_change'] The current path, api/v1/rest-auth/login/, didn't match any of these. settings.py content INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'rest_auth', # Apps 'posts.apps.PostsConfig', ] Below is the content of my urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('posts.urls')), path('api-auth/', include('rest_framework.urls')), path('api/v1/rest-auth', include('rest_auth.urls')), ] I'm not able to figure out, what is wrong with the code. -
Is it possible to pass variables to CSS file in Django
I was wondering is it possible to pass a variable from a Django view to CSS file? Is there any way? I was following some tutorials in a front end design and wondered if it can be built dynamically in Django? .card:nth-child(1) svg circle:nth-child(2){ stroke-dashoffset: calc(440 - (440 * 90) / 100); stroke: #00ff43; } .card:nth-child(2) svg circle:nth-child(2){ stroke-dashoffset: calc(440 - (440 * 80) / 100); stroke: #00a1ff; } .card:nth-child(3) svg circle:nth-child(2){ stroke-dashoffset: calc(440 - (440 * 60) / 100); stroke: #ff04f7; } stroke-dashoffset: calc(440 - (440 * {{ var }}) / 100); can i pass those variables from a view to this var in CSS? this portion of code gives 90, 80 and 60% respectively. -
How to retrieve all the comments for a post using related names?
I am trying to create a comment page for a blog-style site that will list all of the previous comments for a single related post. I am having trouble figuring out how to structure the view to get what I'm looking for. I have been trying to use related names to get the data but am not sure if that is the right method. Here are my models: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=128) content = models.TextField() image = models.ImageField(upload_to='post_pics', blank=True) date_posted = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('home') class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() date_created = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('home') And here is my view: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'home/comment-form.html' fields = ['comment',] def get_context_data(self, **kwargs): context = super(CommentCreateView, self).get_context_data(**kwargs) context['post'] = Post.objects.get(pk=self.kwargs['pk']) comments = Post.comments.all() context['comments'] = comments return context def form_valid(self, form): form.instance.user = self.request.user form.instance.post = Post.objects.get(pk=self.kwargs['pk']) return super().form_valid(form) I have been trying a bunch of different things. The above is just my latest attempt. When I try to run this one I get a 'ReverseManyToOneDescriptor' object has no attribute 'all' error. I don't know if I need to run … -
Getting Base model instance from proxy model
Using proxy model like below. How can I get base model_name from proxy model instance. class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class MyPerson(Person): class Meta: proxy = True -
Passing Foreign Key Through Django Session
I am really stuck on a scenario where I am looking to pass some data through the session in django from one view to another. I am looking to pass data from a dynamic formset (i.e. it may have one form, two forms, or more - no way of knowing). In that one field - ProductCode - is a foreign key so is not json serializable. I will post my code below: models.py class QuoteManifest(models.Model): quote = models.ForeignKey(Quote, null=True, on_delete=models.CASCADE) ProductCode = models.ForeignKey(Product, null=True) DescriptionOfGoods = models.CharField(max_length=500, blank=True) UnitQty = models.CharField(max_length=10, blank=True) Type = models.CharField(max_length=50, blank=True) Amount = models.CharField(max_length=100, blank=True) Price = models.CharField(max_length=100, blank=True) class Product(models.Model): ProductCode = models.CharField(max_length=100) HSCode = models.CharField(max_length=50, null=True) DescriptionOfGoods = models.CharField(max_length=100) Price = models.CharField(max_length=100) UnitType = models.CharField(max_length=100) def __str__(self): return str(self.ProductCode) views.py def QuoteView(request): QuoteManifestForm= modelformset_factory(QuoteManifest, QManifestForm, can_delete = True) if request.method == "POST": form2 = QuoteManifestForm(request.POST) if form.is_valid(): manifestData = form2.cleaned_data product = manifestData.pop('ProductCode') #this is where I get error request.session['manifestData'] = manifestData return redirect('QuotePreview') class QuotePreview(View): def get(self, request, *args, **kwargs): manifestData = request.session.pop('manifestData', {}) context = { 'manifestData': manifestData, } pdf = render_to_pdf('quote_preview.html', context) return HttpResponse(pdf, content_type='application/pdf') forms.py class QManifestForm(forms.ModelForm): class Meta: model = QuoteManifest fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price') When … -
Elastic Beanstalk - AWS
I've researched and couldn't find the solution. click here for see ERRO -
Django Uploaded images not displayed in production
I am aware of this question: Django Uploaded images not displayed in development , I have done everything that it is described, but still can't find a solution. I also have used for reference this: GeeksForGeeks and Django official documentation, however, none of them solved my problem. I have deployed a Django App on a Ubuntu server for the first time using Nginx and gunicorn. Before deployment, I used port 8000 to test if everything runs as it is supposed to and all was fine. Since I allowed 'Nginx Full' my database images are not showing up. This is my django project structure: My virtual environment folder and my main project folder are both in the same directory. I have separated them. # Create your models here. class Project(models.Model): project_name = models.CharField(max_length=120) project_description = models.CharField(max_length=400) project_link = models.CharField(max_length=500) project_image = models.ImageField(upload_to='') def __str__(self): return self.project_name I have set up my settings.py to : # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media' MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', 'media').replace('\\','/') My view gets all the project object from a database and passes those to the template. In my template … -
Is there a way to call a post from another view in Django?
I want to process the POST in Processing view when I type next/ URL directly on the browser bar, any clue? I'm including the repository just in case: https://github.com/ivanperezdesigner/Hypercar thank's for your help views.py file class Processing(View): def get(self, request, *args, **kwargs): context = {'service_line': service_line} return render(request, 'tickets/processing.html', context) def post(self, request, *args, **kwargs): if len(service_line['change_oil']) > 0: service_line['change_oil'].pop(0) elif len(service_line['inflate_tires']) > 0: service_line['inflate_tires'].pop(0) elif len(service_line['diagnostic']) > 0: service_line['diagnostic'].pop(0) return redirect('/next') class Next(View): def get(self, request, *args, **kwargs): x = 0 if len(service_line['change_oil']) > 0: x = service_line['change_oil'][0] elif len(service_line['inflate_tires']) > 0: x = service_line['inflate_tires'][0] elif len(service_line['diagnostic']) > 0: x = service_line['diagnostic'][0] context = {'next': x} return render(request, 'tickets/next.html', context) urls.py file from django.urls import path from tickets.views import WelcomeView, MenuView, Service, Processing, Next from django.views.generic import RedirectView urlpatterns = [ path('welcome/', WelcomeView.as_view()), path('menu/', MenuView.as_view()), path('get_ticket/<str:service>', Service.as_view()), path('processing/', Processing.as_view()), path('next/', Next.as_view()), ] -
why django crispy_forms is failing on ubuntu on my aws ec2 instance
I have created a AWS ec2 instance using python 3.6 django2.2 gunicorn nginx supervisor but now that i have pulled the latest changes from github where i added two dependencies: Pillow crispy_form to install them on ubuntu i did: sudo apt-get install python-pil sudo apt-get install python-django-crispy-forms but now after restarting supervisor and nginx I get a 502 Bad Gateway nginx/1.14.0 (Ubuntu) on the web app page. by checking the log of /var/log/gunicorn/gunicorn.err.log with nano: this is what i found. ModuleNotFoundError: No module named 'crispy_forms' [2020-06-21 00:48:19 +0000] [10606] [INFO] Worker exiting (pid: 10606) Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 209, in run self.sleep() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 357, in sleep ready = select.select([self.PIPE[0]], [], [], 1.0) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/env/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 229, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt self.stop() … -
Model data not displayed on template - django
Short Story: I have made two apps. Properties and Tenants within a django project. First I started rendering data from Property model to property_detail.html template and it works fine, but after I created & migrated the Tenants model, and I try to render data from there to property_detail.html it doesn't work. Yet it doesn't give me any errors. It just doesn't show up. Models.py import arrow import uuid from django.db import models from django_countries.fields import CountryField from django.urls import reverse from django.conf import settings from properties.models import Property class Tenant(models.Model): id = models.UUIDField( # new primary_key=True, default=uuid.uuid4, editable=False) full_name = models.CharField("Full Name", max_length=255, null=True) email = models.EmailField(unique=True, null=True) phone = models.CharField(max_length=20, unique=True, null=True) description = models.TextField("Description", blank=True) country_of_origin = CountryField("Country of Origin", blank=True) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) created_on = models.DateTimeField( "Created on", auto_now_add=True, null=True) is_active = models.BooleanField(default=False) apartment = models.ForeignKey( Property, on_delete=models.CASCADE, related_name='reviews', ) rent_tenant = models.CharField( "Rent he/she pays", max_length=10, blank=True) def __str__(self): return self.full_name def get_absolute_url(self): """"Return absolute URL to the Contact Detail page.""" return reverse('tenant_detail', kwargs={'pk': str(self.pk)}) urls.py from django.urls import path from .views import TenantListView, TenantDetailView urlpatterns = [ path('', TenantListView.as_view(), name='tenant_list'), path('<uuid:pk>', TenantDetailView.as_view(), name='tenant_detail'), # new ] views.py from django.views.generic import ListView, DetailView … -
what payment gateway should i use in django
hi i am new to django maybe few months ago,but successfully created a website but it needed a payment Gateway now i want to ask is their any *third party used for payment in django built in django-payment gateway or how do i go about the payment method* i have tried using Stripe but its does not work for my country because its not in the list of countries its working with Note= if their is any tutorial i can follow with any recommended payment gateway, kindly provide -
Django notify when model changes
I have a big legacy Django1.11 project and I want to make some changes on a table. I needed to be notified (notification is not a big deal here and suppose i just want to print "hello world" in case of happening) when every change on this table happens (every insert or or update in rows) and I can not be sure I can find all of this changes in code because it is so big. I searched and I figured out if I override save method in Model I will be notified in some cases and still i will be missing some changes in rows. For example when Model.objects.filter().update() I will be missing changes. I wanted to know Is there a way that I can be sure that I will catch every happens in rows of Model table? -
How to send a variable from Django template to view
I am trying to send a number from the template page (.html) to views.py. For this, I did the following things: urls.py path('video/<int:value>', views.process_number, name='video_lab'), .html <div class="frame"> <span id="currentFrame">0</span> </div> <div class="btn-group" > <button id="stop_bttn_id" class="btn btn-primary btn-lg" name="stop_bttn">Take Number</button> </div> <script type="text/javascript"> function btn_click() { var x = document.getElementById('currentFrame').textContent fetch("{% url 'video_lab' value=x %}", { method: "POST", headers: { "X-CSRFToken": '{{csrf_token}}'}, body: 'true' }).then(response => { return response.json() }) } document.getElementById('stop_bttn_id').addEventListener('click', btn_click); </script> views.py @login_required def process_number(request, value: int): json_response = {....} return JsonResponse(json_response) Here is the problem. If I directly send a number instead of variable, then the number can be sent to the views.py. fetch("{% url 'video_lab' 5 %}" However, if I try to send a variable, I get an error: NoReverseMatch at /video/ Reverse for 'video_lab' with keyword arguments '{'value': ''}' not found. 1 pattern(s) tried: ['video/(?P[^/]+)$'] I also tried: fetch("{% url 'video_lab' x %}" Although I did lots of research, I could not find any solution. Could anyone help me about it? Best. -
Saving lists to models in Django
I'm building a tracker where users save their response to the same question every day. Is there a way to track individual responses as a list through models.py? I don't see a model field for lists, so I'm saving the list of responses through views.py at the moment. mylist = [] global length @login_required def add(request): respond = Response.objects.all() if request.method == 'POST': selected_option = (request.POST['rating']) length = len(mylist) if selected_option == 'option1': mylist.append(1) print(respond.score) elif selected_option == 'option2': mylist.append(2) print(respond.score) elif selected_option == 'option3': mylist.append(3) print(respond.score) elif selected_option == 'option4': mylist.append(4) print(respond.score) elif selected_option == 'option5': mylist.append(5) print(respond.score) else: return HttpResponse(400, 'Invalid form') for votes in respond: votes.save() return redirect(add) context = { 'respond' : respond, 'mylist' : mylist } return render(request, 'rating/add.html', context) def graph(request): x_data = list(range(0,len(mylist))) y_data = list(mylist) return render(request, "rating/home.html", context={'plot_div': plot_div, 'mylist' : mylist}) This accomplishes my need to save responses to a list so that I can send them over to a plot. The issue is that it doesn't save as part of the model and as such is not linked directly to any specific user (all user results are grouped together). I'm using this for my models file right now but … -
Create Pre-Populated Database Models
I have an online learning website with modules students can enroll in. Each module contains a set of 5 classes. To do this I intend to: On enrollment, an empty one-to-many 'learning module' instance is created and attached to the student (a student can have many modules, but a module instance can only have one student). Superusers can assign modules to students (preferably in Django's Admin and by going to Student). On doing this, the module's classes are copied into the students 'learning module' db instance at the click of a button? Students can view their modules. If the student has multiple modules, modules will be separated with a space My question is how can I create these modules class lists and store them, ready to be copied into a students 'learning module' database instance? Basically I need to store pre-filled database fields which can be copied to a database instance at the click of a button. I know of data fixtures, but this seems more for initially populating a database and is done with shell. My next problem will be finding out how to allow superusers to assign these modules to Students within Django Admin. Thank you. -
Linking a HTML button to run a python script in django
I want to run my python file when a html button is pressed. I have my python file working when i press run in PyCharm (it just creates a graph). My python file is stored as main.py. I am having trouble linking the html button to run the main.py file when the button is pressed. At the moment I think i have the button pointing to a function in my views.py which in turn runs my main.py file. (or so i think. it is not working) INDEX.HTML <input type="button" value="Run graph" onclick="run_graph()"> URLS.PY from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('run_graph', views.run_graph), ] VIEWS.PY def run_graph(main): return main MAIN.PY import matplotlib.pyplot as plt import numpy as np col_count = 3 bar_width = .1 korea_scores = (554, 536, 538) canada_scores = (518, 523, 525) china_scores = (613, 570, 580) france_scores = (495, 505, 499) index = np.arange(col_count) k1 = plt.bar(index, korea_scores, bar_width, alpha=.4, label="Korea") c1 = plt.bar(index + bar_width, canada_scores, bar_width, alpha=.4, label="Canada") ch1 = plt.bar(index + 0.2, china_scores, bar_width, alpha=.4, label="China") f1 = plt.bar(index + 0.3, france_scores, bar_width, alpha=.4, label="france") plt.ylabel("mean score in PISA 2012") plt.xlabel("Subjects") plt.title("France") plt.xticks(index + .3 / 2, ('Maths', …