Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy my django site using iis via specific name
I deployed my site in iis and clients can access with tow way : 1-ip:port (8080) 2- servername:port How can deploy it on the specific url name like : Servername/xxx/yyyy/ Without shown port, ??? Point: I used default port for another project on this server and dns server resolved to this ip server Many years ago. -
What's the most efficient way to retrieve django queryset with the hightest number of posts for a related name?
I'm currently working on a website where advertisements will be posted to display vehicles for sale and rent. I would like to retrieve a queryset that highlights only one car brand (i.e. Audi) which has the highest number of posts for the respective model. Example: Displaying the Audi brand because it has the highest number of related posts. My question is, what's the most efficient way of doing this? I've done some work here but I'm pretty sure this is not the most efficient way. What I have is the following: # Algorithm that is currently retrieving the name of the brand and the number of related posts it has. def top_brand_ads(): queryset = Advertisement.objects.filter(status__iexact="Published", owner__payment_made="True").order_by('-publish', 'name') result = {} for ad in queryset: # Try to update an existing key-value pair try: count = result[ad.brand.name.title()] result[ad.brand.name.title()] = count + 1 except KeyError: # If the key doesn't exist then create it result[ad.brand.name.title()] = 1 # Getting the brand with the highest number of posts from the result dictionary top_brand = max(result, key=lambda x: result[x]) # Returns for i.e. (Mercedes Benz) context = { top_brand: result[top_brand] # Retrieving the value for the top_brand from the result dict. } print(context) # … -
My article doesn't display in article_details
I want to show my articles but My article doesn't display on article_details.html This is what my site looks like. You can see only my article's title works. My models.py: class Article(models.Model): title = models.CharField(max_length=50, verbose_name="Title") mini_description = models.TextField(max_length=100, default='', verbose_name='Mini_description') content = models.TextField(blank=True, verbose_name="Content") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Date of add") updated_at = models.DateTimeField(auto_now=True, verbose_name="Update date") photo = models.ImageField(upload_to='photos/', verbose_name="Photo") is_published = models.BooleanField(default=True, verbose_name="Is published") category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category") def get_absolute_url(self): return reverse("article_details", kwargs={'pk': self.pk}) def __str__(self): return self.title def __repr__(self): return f"Article(pk={self.pk}, title='{self.title}')" class Meta: verbose_name = "Article" verbose_name_plural = "Articles" ordering = ['-created_at'] My views.py: class ArticleDetails(ArticleListByCategory): model = Article context_object_name = 'article' template_name = 'blog/article_details.html' def get_queryset(self): article = Article.objects.filter(pk=self.kwargs['pk'], is_published=True).select_related('category') return article def get_context_data(self, **kwargs): context = super().get_context_data() article = Article.objects.get(pk=self.kwargs['pk']) context['title'] = f"Article: {article.title}" return context My article_details.html: {% extends "base.html" %} {% load static %} {% block style %} <link href="{% static 'blog/css/main.css' %}" rel="stylesheet"> {% endblock style %} {% block title %} {{ title }} {% endblock %} {% block main %} <section class="articles" id="articles"> <div class="card_details"> <h1>{{ article.title }}</h1> <p><em>{{ article.mini_description }} </em> </p> <img src=""> <div class="description"> <p> {{ article.content }} </p> </div> <div class="card-footer text-muted"> {{ article.created_at| timesince }} … -
Fetching html form data in django
I have created one html form for my web application. Now I want to fetch data for further validation on submit the form in DJANGO. So how can I do this. I have attached my html form code below. Actually, I can get the data by the request.POST.get('field_name') method but I want to get data in the single object. Also I want to create seprate python file for validation. So how can I redirect on that file. <form action="/contact_form_data_insert" name = "contact_us_form" id = "contact_us_form" method="POST"> <div class="bg-transperent container mt-6"> <div class="bg-transperent container"> <div class="row bg-transperent"> <div class="col-lg-6 bg-transperent contact_field"> <div class="form-outline my-2 px-2" > <input type="text" id="contact_name" name="contact_name" class="form-control form-control-lg-border-0" placeholder = "Your Name"/> </div> </div> <div class="col-lg-6 bg-transperent contact_field"> <div class="form-outline my-2 px-2" > <input type="text" id="contact_company" name="contact_company" class="form-control form-control-lg-border-0" placeholder = "Your Company" /> </div> </div> </div> <div class="row bg-transperent"> <div class="col-lg-6 bg-transperent contact_field"> <div class="form-outline my-2 px-2" > <input type="tel" id="contact_phone_number" name="contact_phone_number" class = "form-control form-control-lg-border-0" placeholder = "Phone Number"> </div> </div> <div class="col-lg-6 bg-transperent contact_field"> <div class="form-outline my-2 px-2" > <input type="email" id="contact_email" name="contact_email" class="form-control form-control-lg-border-0" placeholder = "Email"/> </div> </div> </div> </div> <div class="bg-transperent container"> <div class="row"> <div class="col-12 bg-transperent contact_field "> <div class="form-outline … -
django-HttpResponse returned None
I am getting an error while I run my project: ValueError: The view ... didn't return an HttpResponse object. It returned None instead. I have seen other questions like this, but their answers don't seem to work. For my other projects the same code worked. I searched on the net for days but I haven't had any luck. views.py - from .models import create_message from .forms import MessageForm from django.http import HttpResponseRedirect def create_message(request): submitted = False if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/create_message?submitted=True') else: form = MessageForm if 'submitted' in request.GET: submitted = True return render(request, 'send/create_message.html', {'form': form, 'submitted': submitted}) forms.py - from django.forms import ModelForm from .models import create_message class MessageForm(ModelForm): class Meta: model = create_message fields = ('message', 'app_name', 'time') labels = { 'message': 'Message', 'app_name': 'App', 'time': 'Time', } widgets = { 'message': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Message'}), 'app_name': forms.Select(attrs={'class':'form-select', 'placeholder': 'App'}), 'time': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Hours : Minutes : Seconds / Hours : Minutes : 00(ZERO ZERO)'}), } models.py - from django.db import models class create_message(models.Model): message = models.TextField(blank=False, null=False) time = models.TimeField(blank=False, null=False) def __str__(self): return self.time create_message.html {% extends 'send/base.html' %} {% block content %} {% if submitted %} Submitted … -
While trying to reverse a url in django template html file, exception 'NoReverseMatch' occurs. I included the additional parameter in views function
def entry(request, name): content = util.get_entry(name.strip()) if content == None: content = "## Page was not found" content = markdown(content) return render(request, "encyclopedia/entry.html", {'content': content, 'title': name}) def edit(request,title): content = util.get_entry(title.strip()) if content == None: return render(request, "encyclopedia/edit.html", {'error': "404 Not Found"}) if request.method == "POST": content = request.POST.get("content").strip() if content == "": return render(request, "encyclopedia/edit.html", {"message": "Can't save with empty field.", "title": title, "content": content}) util.save_entry(title, content) return redirect("entry", name=title) return render(request, "encyclopedia/edit.html", {'content': content, 'title': title}) util has files that help get names of entered files, save a new entry or get content of entry. {% extends 'encyclopedia/layout.html' %} {% block title %} {{title}} {% endblock %} {% block body %} <a href="{% url 'edit' title %}" class="badge badge-info">Edit This Page</a> {{entry | safe }} {% endblock %} layout has the standard block code of HTML edit.html contains HTML code that gives a button on each page so that we can edit the content of the page entry and passes name='content' for the content to be edited. THIS IS A CS50w project and I have taken references from other sources. -
Not able to fetch the image from database in django application
In my application, I am able to fetch all the other contents like name description but instead of using the all code correctly and all things may be clear the images are not loading.. please help click to see image -
Execute custom SQL directly and display on page
I want to do something like... views.py from django.http import HttpResponse from django.db import connection def query(self): with connection.cursor() as cursor: cursor.execute('SELECT some, stuff FROM here;') row = cursor.fetchall() return row def index(request): return HttpResponse(query(self)) It doesn't work (yet) -
Django: Storing static folder on S3 bucket leading to the css, and js files not working
I have js, images, and CSS folders inside the static folder. They are stored in the S3 bucket. Unless I give public access, my app cannot load the CSS files, images, and javascript files. My app relies on the js files (jQuery) for all interactions (API calls - for Ajax). What specific permission would I have to set on the S3 bucket to allow my app to read or execute the js files, but not allow anyone to download or view them (when they put the fully qualified URL on the browser)? -
Block content not rendering
I want to retrieve all posts from my Post model on one view template(allposts.html), and all posts from the politics category on another view template(political.html), and then display them on different sections of the index.html template. However, I am getting a blank page. What could be the issue? Here is my code index.html <!-- ======= Post Grid Section ======= --> <section id="posts" class="posts"> <div class="container" data-aos="fade-up"> <div class="row g-5"> {% block allposts %} {% endblock %} <!-- Some sections skipped --> <div> <div class="post-meta"><span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>Jul 5th '22</span></div> <h3><a href="single-post.html">What is the son of Football Coach John Gruden, Deuce Gruden doing Now?</a></h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio placeat exercitationem magni voluptates dolore. Tenetur fugiat voluptates quas, nobis error deserunt aliquam temporibus sapiente, laudantium dolorum itaque libero eos deleniti?</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="assets/img/person-2.jpg" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">Wade Warren</h3> </div> </div> </div> </div> {% block content %} {% endblock %} Here is the political.html content that I am trying to render {% extends 'index.html' %} {% block content %} {% for politics in politics %} <div class="row"> <div class="post-entry-1 border-bottom"> <a href="single-post.html"><img src="{{post.image.url}}" alt="" class="img-fluid"></a> <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> … -
How to cache django rest framework (retrieve) with persistent cache
I have the following Django REST view: class AnnotationViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Annotation.objects.all() serializer_class = AnnotationSerializer Accessing a single method will call the retrieve function thanks to mixins.RetrieveModelMixin. I would like to speed up the function since it requires multiple queries and it uses a lot of CPU. In particular: I'd like a persistent cache that could be used after restarting the application The cached data needs to be different based on the record retrieved (e.g. http://127.0.0.1/annotations/1 vs http://127.0.0.1/annotations/2, etc) As of now I tried to overwrite the view retrieve method: @method_decorator(cache_page(60 * 60 * 24 * 365)) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) and to set the default cache to disk: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/home/django_cache', } } I don't think it is working, as I need to cache about 2 million items (I have about 2 millions records): the folder /home/django_cache uses less than a Mb and it's size changes every time I call the API. -
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') with unique_togther field
I am having the same issue as the user from this post, however, all of the proposed solutions did not work for me. I am using MySQL 8.0.24 with Django 3.1. Similar to them, I had a model without a unique_together field as shown below class Show(models.Model): english_name = models.CharField(max_length=400) kanji_name = models.CharField(max_length=200, blank=True) romanji_name = models.CharField(max_length=400, blank=True) show_type = models.CharField(max_length=100, blank=True) # a bunch of other fields... class Meta: verbose_name_plural = 'Series' ordering = ('-created',) unique_together = ['english_name', 'kanji_name', 'romanji_name', 'show_type'] def __str__(self): return self.english_name It was only until I changed class Meta to this class Meta: verbose_name_plural = 'Series' ordering = ('-created',) unique_together = ['english_name', 'kanji_name', 'romanji_name', 'show_type'] That I started receiving this error whenever I migrated my database. django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') I followed the steps in the post I linked above to ensure the utf8 was used, I was able to confirm that the dataset was using that character set, but it didn't resolve my issue. Is there anything else I can do to ensure that the unique_together field can be used? -
How do I overlay text on a PDF file scanned as an image?
I cannot figure out how to overlay variables as text on to a PDF uploaded as a scanned document. The use scenario is to process the PDF and place text in it as though the PDF is a background image. Text is unremarkable, and the process is intended to produce a customized PDF for the user. I was trying to use XHTML2PDF... I might be going in the wrong direction. How would I do that? -
Django Home url set to folder
I have an issue where I would like my address (whether local or live) to point to my projects app as my home page, yet every change I make breaks the other URLs. My main site URL patterns are: urlpatterns = [ path('admin/', admin.site.urls), path("projects/", include("projects.urls")), path("blog/", include("blog.urls")), ] I have tried to change the path("project/", include("projects.urls")) to path("", include("projects.urls")) which breaks the blog index. my blog has the following pattern: urlpatterns = [ path("", views.blog_index, name="blog_index"), path("<slug:slug>/", views.blog_detail, name="blog_detail"), path("<category>/", views.blog_category, name="blog_category"), ] And my projects: urlpatterns = [ path("", views.project_index, name="project_index"), path("<slug:slug>/", views.project_detail, name="project_detail"), path("project/<tag>/", views.project_tag, name="project_tag"), ] -
Reverse for 'orderlist_order_change' with arguments '('',)' not found. 1 pattern(s) tried: ['orderlist/order/(?P<object_id>.+)/change/\\Z']
I need the form to insert the id value on save when using django admin models.py class Order(models.Model): id = models.CharField(max_length=32,primary_key=True)# customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ... admin.py class OrderAdmin(admin.ModelAdmin): readonly_fields = ['id'] def save_model(self, request, obj, form, change): form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999)) form.save() super().save_model(request, obj, form, change) error: NoReverseMatch at /orderlist/order/add/ Reverse for 'orderlist_order_change' with arguments '('',)' not found. 1 pattern(s) tried: ['orderlist/order/(?P<object_id>.+)/change/\Z'] Request Method: POST Request URL: http://127.0.0.1:8057/orderlist/order/add/ Django Version: 3.2.10 Exception Type: NoReverseMatch Exception Value: Reverse for 'orderlist_order_change' with arguments '('',)' not found. 1 pattern(s) tried: ['orderlist/order/(?P<object_id>.+)/change/\Z'] Exception Location: E:\CodeFiles\Venv\py378django3.2\lib\site-packages\django\urls\resolvers.py, line 698, in _reverse_with_prefix Python Executable: E:\CodeFiles\Venv\py378django3.2\Scripts\python.exe Python Version: 3.7.8 -
how to implement Graphql Proxy in python
I'm trying to build a simple Graphql proxy service that receives graphql requests and forwards them to a remote server and I can return the response to the main server. I am using Django for the main project and the remote server is also using Django graphene to return. -
Constant deletion routine can harm the performance of the database or application?
I created a view that does some checks between models as these models are updated/added. When this check finds an inconsistency it creates a record and a specific model of record of inconsistencies. My question is about the strategy I used in this view. view def farm_check(farm_id): farm = get_object_or_404(Farm, pk=farm_id) to_delete = FarmProblem.objects.filter(farm=farm) for delete in to_delete: delete.delete() check_city = Registration.objects.filter(farm=farm).filter(~Q(city=farm.city)) check_uf = Registration.objects.filter(farm=farm).filter(~Q(uf=farm.uf)) check_car = Registration.objects.filter(farm=farm,car__isnull=True) check_ccir = Registration.objects.filter(farm=farm,ccir__isnull=True) check_nirf = Registration.objects.filter(farm=farm,nirf__isnull=True) check_area = Registration.objects.filter(farm=farm,area__isnull=True) list_area_pk = map(lambda x: x.pk,check_area) check_app = Registration.objects.filter(farm=farm,app__isnull=True).exclude(pk__in=list_area_pk) for check in check_city: problem = 'Cidade inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='City',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='City',specific=check.number,item=problem) item.save() for check in check_uf: problem = 'UF inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='UF',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='UF',specific=check.number,item=problem) item.save() for check in check_car: problem = 'CAR inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='CAR',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='CAR',specific=check.number,item=problem) item.save() for check in check_ccir: problem = 'CCIR inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='CCIR',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='CCIR',specific=check.number,item=problem) item.save() for check in check_nirf: problem = 'Sem número de NIRF' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='NIRF',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='NIRF',specific=check.number,item=problem) item.save() for check in check_area: problem = 'Área indeterminada' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='Area',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='Area',specific=check.number,item=problem) item.save() for check in check_app: problem … -
Add Custom bootstap template to Django CMS Project
I hope you are well. The reason i'm writing to you is because ive been utilizing the Django cms bootstrap carousel plug in. Im all set however i am struggling to figure out how to add me newly added custom template to my application. Im wondering if there is something i need to add to my settings.py file like CAROUSEL_TEMPLATES = [ ' ' ] I would be very grateful if you could point me in the right direction? -
Django view function isnt working correctly
so the basic goal of my project is to allow teachers and admin to login to the system and take attendance for the students. my new issue is that i have a view function that is suppose to check to see if students student is already added to the respective class and if they are it will exclude them from the drop down menu and display the students who aren't in the class but it not doing that instead it is showing me a blank drop down menu. the way i have it set up is that the admin clicks the add student button then it will convert a .html page to modal which brings up the list of students to select from. When i add the form responsible for saving the student to the class in the Django admin it work perfect but i cant seem to get it to work in the user section Ui. I am new to Django and this is my first project so any help is really appreciated Views #check to see if students already exist in class and display those who aint to be added @login_required def manage_class_student(request, classPK=None): if classPK is None: … -
Creating a subForm within a Form to populate an Abstract Form
I have been trying to figure this out by banging my head and scouring the forums and Google. Hope someone has had experience with this. I am trying to create some text mining subform within PostForm Class that calls a script.So an user enters a DOI or PMID and searches the PUBMED database.I am successful with the script pulls data from a server, but would like to figure out the user then continues to fill the rest of the data. So together with the Called data and the User entry save as post. Here I am using the Django-Machina Blog as the platform. So a User would enter a DOI or PMID, returns a query, that a user can then enter information in contents. [Form][1] AbstractModel: class AbstractPost(DatedModel): """ Represents a forum post. A forum post is always linked to a topic. """ topic = models.ForeignKey( 'forum_conversation.Topic', related_name='posts', on_delete=models.CASCADE, verbose_name=_('Topic'), ) poster = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='posts', blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Poster'), ) anonymous_key = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Anonymous user forum key'), ) # Each post can have its own subject. The subject of the thread corresponds to the # one associated with the first post subject = models.CharField(verbose_name=_('Subject'), max_length=255) doi … -
Django Generating Custom ID
Okay so, I have seen numerous "answers" to this question, most notably, this one. from django.db.models import Max id = models.CharField(primary_key=True, editable= False, max_length=10) def save(self, **kwargs): if not self.id: max= Custom.objects.aggregate(id_max=Max('id'))['id_max'] self.id= "{}{:05d}".format('IT-', max if max is not None else 1) super().save(*kwargs) Now, thanks to this, I really just apply the code to my model, and it should work. Well, it doesn't. It wants to, but it can't, let me explain: on the backend of the django application I tried adding a new row, but when saving it, it throws an OperationalError, (1366, "Incorrect integer value: 'IT-00002' for column id), (my prefix being 'IT-'). Now, from what I can gather, the prefix is being included yes, but the column isn´t changing from integer. I have saved, migrated all changes and it isn´t working. I have even tried changing the data type in phpmyadmin, but because it also has the 'AUTO_INCREMENT' property, it can't be changed to anything other than an integer. How can I change this? -
TypeError: cannot unpack non-iterable function object while using get() in Django
I have a model called WatchList with a object called listing which corresponds to the Listings model. I want to make a page where all the listings that a user has added to his watchlist appear. I am trying to filter through the WatchList objects through the user and get access to the listing object, so I can get all the objects from that particular listing (there may be more than one). views.py def watchlist(request): watchlists = WatchList.objects.filter(user=request.user) watchlist_listing = watchlists.get(listing) listings = Listings.objects.all().filter(watchlist_listing) return render(request, "auctions/watchlist.html",{ "listings": listings }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class WatchList(models.Model): listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") error message TypeError: cannot unpack non-iterable function object This error is caused by this line watchlist_listing = watchlists.get(listing) . But if I change the code to watchlist_listing = watchlists.get('listing') this error too many values to unpack (expected 2) occurs. How do I fix this and get access … -
Why does Django related_name isn't working
I am working in my Django (DRF) app. I have these models class CustomUser(AbstractBaseUser, PermissionsMixin): ... class SupportChat(models.Model): support = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="support_chat" ) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="chat" ) I want to get chats of the users in views.py @api_view(['GET']) def get_my_chats(request): res = {} admins = CustomUser.objects.filter(user_type='Admin') res["admins"] = CustomUserSerializer(admins, many=True).data #my_request_chats = SupportChat.objects.filter(user=request.user) my_request_chats = request.user.chat if my_request_chats is not None: res["my_request_chats"] = SupportChatSerializer(my_request_chats, many=True).data res["my_request_chats"] = None my_response_chats = SupportChat.objects.filter(support=request.user) if my_response_chats is not None: res["my_response_chats"] = SupportChatSerializer(my_response_chats, many=True).data res["my_response_chats"] = None return Response(res) Problem -- Can't get chats of the user (my_request_chats is NULL) Received response like this { "admins": [ // valid data ], "my_request_chats": null, "my_response_chats": null } I checked that request.user have chats (in admin panel) -
Django resize chart in table
I have a basic chart created with chart.js which is later displayed in table. I have a problem to manipulate his height/width to fit it correctly to table in django template. Chart is displayed in for loop in table and code looks like: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> <table class="table table-bordered"> <thead>Details </thead> <tbody> {% for key, value in game_details.items %} <tr> <th>Game</th> <th>Played</th> <th>Won</th> <th>Lost</th> <th>Pending</th> </tr> <tr> <td>Game </td> <td>{{ value.all }}</td> <td>{{ value.win }}</td> <td>{{ value.lost }}</td> <td>{{ value.pending }}</td> </tr> <tr> <td colspan="5" style="max-height: 10px"> <canvas id="myChart{{ key }}" width="200" height="200"></canvas> <script> const ctx{{ key }} = document.getElementById('myChart{{ key }}').getContext('2d'); const myChart{{ key }} = new Chart(ctx{{ key }}, { type: 'doughnut', data: { labels: ['W', 'L', "P"], datasets: [{ label: '# of Votes', data: [{{ value.win }}, {{ value.lost }}, {{ value.pending }}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(153, 102, 255, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(153, 102, 255, 1)', ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </td> </tr> {% endfor %} </tbody> </table> and it looks like that: Changing the width or height … -
NameError: name 'Any' is not defined in Django
When I use the autocomplete suggestion in VSCode to make a get_context_data() function: def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: return super().get_context_data(**kwargs) I get a NameError: NameError: name 'Any' is not defined I am new to using type hints in Python - do I need to import something for type Any?