Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template language "If" statement with many "and"
Basically i want to add a class to a div based on whether some variables have content or not. This is the If statement: <div class="search__container {% if images == true and blogs != True and parks != True %} only-images {% elif blogs == true and images != True and parks != True %} only-blog {% elif parks == true and blogs != True and images != True %} only-parks {% elif parks == true and blogs == true and images != True %} only-parks-blogs {% elif parks == true and images == true and blogs != True %} only-parks-images {% elif images == true and blogs == true and parks != True %} only-images-blogs {% endif %}" > This way it's not adding any class under any circumstances. If instead i remove the == and replace the != with is not it'll always take the first if as True and add the class only-images -
Dúvida sobre Django Queryset
Gostaria de saber se alguém consegue me ajudar na seguinte questão: last = Jogos.objects.all().filter(concurso = 2248) Nesse código acima a variável fica com o valor <QuerySet [<Jogos: 2248>]> porém eu gostaria de imprimir não isso e sim os valores do concurso 2248, o que estou fazendo errado ? -
How to add missing Months in Django Python List of Dictionary
<QuerySet [{'month': datetime.datetime(2021, 4, 1, 0, 0, tzinfo=), 'total': 1}, {'month': datetime.datetime(2021, 6, 1, 0, 0, tzinfo=), 'total': 1}]> How to add Missing Month of May (5) in which 'total' is equal to Zero in above? -
How to pass 'pk' to class-based view
This is my urls.py: urlpatterns = [ path('<int:pk>/', views.PortfolioDetailView.as_view(), name='index'), ] And my views.py: class PortfolioDetailView(DetailView): queryset = Project.objects.get(pk=pk) template_name = 'portfolio/index.html' context_object_name = 'projects' I'm obviously missing something (and I'm sure it's a silly one) because I get error: queryset = Project.objects.get(pk=pk) NameError: name 'pk' is not defined What is it? -
ImportError at / cannot import name 'register_new_org_view' from 'users.views' (/home/ubuntu/xyz/users/views.py)
I am having trouble with my gunicorn, nginx deployed django application. Everything runs smoothly on my local development and python manage.py check does not throw any errors. However, as soon as I deploy my application to my server this error is thrown:ImportError at / cannot import name 'register_new_org_view' from 'users.views' (/home/ubuntu/xyz/users/views.py) I have defined the view and import it correctly... other views from other apps are working perfectly fine... what can be the reason? Thank you so much for your help! -
Django - ModuleNotFound
Currently trying to implement a script within a Django application, however I am getting a module not found error when trying to execute the Django app. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line … -
DateField format in DjangoTemplate
I am using paginator to divide reviews on pages, my model has DateField created = models.DateField(auto_now_add=True) I am using ajax to do it without refreshing page. When i put it in my template like this {{review.created}} It displays in format like 06 June 2021 But with ajax, where i pass 'date':obj.created It displays in format 2021-06-06 How can i made it to display similiar in one of these formats? I prefer first format, but second will be acceptable too -
Issue installing and configuring GeoDjango
I am following the following tutorial with creating a Geo Location based web app. Although, I've ran in to a few challenges which I've been trying to figure out how to resolve. Reference to GeoDjango tutorial: https://realpython.com/location-based-app-with-geodjango-tutorial/ Per the instructions (on the link provided above) - I have included django.contrib.gis as apart of my Installed Apps. Although, Gunicorn is failing to start when this include is in place. So I'm guessing it will most likely be because I need to install other relevant libraries in order to get GeoDjango working. I did a little digging online and came across this link - https://docs.djangoproject.com/en/3.2/ref/contrib/gis/install/geolibs/ Which seems to references the libraries which need to be installed. I have managed to install GEOS and PROJ perfectly fine. Although, the final requirement is to install GDAL. So I found the relevant install command for GDAL pip3 install gdal but I am receiving the following error when installing this library within the SSH console. Running setup.py install for gdal ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3.6 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xjvcvnos/gdal_5ab038f0da3b44488d8b78e9cb9b461a/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xjvcvnos/gdal_5ab038f0da3b44488d8b78e9cb9b461a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code … -
testdriven.io django docker tutorial error on test CI section
Cannot get the CI section complete because pytest fails. looking at the logs of the test build it errors with a sqlite3 error when it's supposed to be connecting to the postgres container that's launched for the tests. need some help figuring out where the error might be. I made my gitlab project public and will include a link directly to the error. https://gitlab.com/hectormalvarez1/mgdusa/-/jobs/1322478542 -
Request.user has no attribute user when used in settings.py
request.user generates a AttributeError: 'WSGIRequest' object has no attribute 'user' error when I try to use it in my settings.py file. Am I doing something wrong? Settings.py: def show_toolbar(request): if DEBUG: return True #if not request.is_ajax() and request.user and request.user.UserSettings.debugger: # return True return False DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': 'acacia2.settings.show_toolbar', } -
How to solve decimal.InvalidOperation on the server?
Info: I have a project where frontend is on ReactJS, and backend is on Django. The problem: When customer placing an order, the server returns 500 InvalidOperation at /api/orders/ [<class 'decimal.InvalidOperation'>] Additional info: It works perfect on test server, but fails on live. The docker containers and back/front code are the same. Taken efforts: rows like round(Decimal((obj.total_price * 100)) / discount_revers - Decimal(obj.total_price), 2) i transform into round(((Decimal(obj.total_price) * Decimal(100))) / discount_revers - Decimal(obj.total_price), 2) and the error still the same. The Question: How to solve this? -
Django testing custom signal arguments with assertIsInstance: AssertionError: <class 'path.to.Foo'> is not an instance of <class 'path.to.Foo'>
I am using Django 3.2 I have written an app that raises custom events, and I am writing tests for the apps. Here is the relevant section of my code: class TestAppModel(TestCase): # .. set up instance variables etc. def test_liked_signal_emits_correct_data(self): self.signal_was_called = False self.sender = None self.instance = None self.event_type = None self.actor = None def handler(sender, instance, event_type, actor, **kwargs): self.signal_was_called = True self.sender = sender self.instance = instance self.event_type = event_type self.actor = actor item_liked.connect(handler) self.daddy.like(self.admin_user) # Check that the sender is a Foo self.assertIsInstance(self.sender, Foo) # <- Nonsensical error emitted here When I run the test, I get the error message: AssertionError: <class 'social.models.Foo'> is not an instance of <class 'social.models.Foo'> Which obviously, is a nonsensical error message that doesn't help me solve the problem. My question is why am I not able to check the instance type using assertIsInstance, and how do I check the class type in the signal receiver? -
How do i resolved user's post name which display email instead of their full name in a social media app am creating?
Am currently working on a social media up in Django but am facing a challenge with the post model app since it displays their email address, when they post a pic or a write feed post instead of their full name! My user model authenticate with email address rather than users name. I don't know if this is the actually course of the problem! How do i get users full name on their post instead? I still want to be able to authenticate users with email but their post should be displayed in their full name. Here my user's model class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email,username,last_name, password, **extra_fields): values = [email,username] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, first_name,last_name, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email,username, first_name,last_name, phone_number, password, **extra_fields) def create_superuser(self, email, username,phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email,username,phone_number, password, **extra_fields) class User(AbstractBaseUser, … -
DNS record look up with Python / Django [dnspython]
I am trying to get DNS records of particular domain. So, I found dnspython package where it could be easily done. It works fines when I run it from my computer. However, when I call it from Django views it shows the previous records (old records) which means it's not updating. Is it some kind of caching in OS level? Note that, I am also using Docker. Restarting docker and clearing cache in Django didn't help, still shows old records. Here's the sample code for checking records: import dns.resolver result = dns.resolver.resolve("domain.com", "TXT")[0].to_text() The code snippet above works and shows any update in TXT record, when I run it from my computer. However, in Django it stucks in old records and not updating. Thanks for any help. -
Im not able to install mysqlclient on macOS
Im trying to connect Django with mySql, but I'm running into an error. I already have mySql installed, and I've already try reinstalling openssl, but I'm still getting the same error. Im on macOs 11.4 and I'm using python 3.9.2 alongside Django 3.2.3. Im getting the following error message when typing on terminal pip3 install mysqlclient: Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-record-6ggb6_as/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/mysqlclient cwd: /private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/ Complete output (44 lines): mysql_config --version ['8.0.25'] mysql_config --libs ['-L/opt/homebrew/Cellar/mysql/8.0.25_1/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/opt/homebrew/Cellar/mysql/8.0.25_1/include/mysql'] ext_options: library_dirs: ['/opt/homebrew/Cellar/mysql/8.0.25_1/lib'] libraries: ['mysqlclient', 'zstd', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/opt/homebrew/Cellar/mysql/8.0.25_1/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] running install running build running build_py creating build creating build/lib.macosx-10.9-universal2-3.9 creating build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb creating … -
How to assign multiple classes to the django form widget's parameter - "attrs"?
This is my simple forms.py: class SearchForm(forms.Form): search = forms.CharField( label="", max_length=100, widget=forms.TextInput( attrs={ "class": "form-control me-2", "type": "search", "aria-label": "Search", } ) ) form.html: <form class="d-flex" method="GET" action="."> {% csrf_token %} {{ form.as_p}} <!-- <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> --> <button class="btn btn-outline-success" type="submit">Search</button> </form> I need my input tag have two bootstrap classes "form-control" and "me-2", but separating them with whitespace in widget's attrs dictionary seems doesn't work. Any suggestions? -
Django or NodeJS for long-term web and business project?
Good afternoon all, we are struggling to decide which way to go for a project and would like to have some insight from people who have been dealing with this. We have to invest in training/time for the two people who are working on our business and we would like to understand which way to go. The people Both have a good understanding of HTML, CSS, SASS and some JS One has some experience with PHP One has more experience with Python The Project Database driven website that will host and display hundreds of products (laboratory products which will need specific templates for each product Shopping chart for reagents and lower cost products A section with a knowledge base The website(s) will be multilingual, with different products for different countries Integrated CRM, connected to the products, stock management and shopping chart Potentially (desirable, but not necessary) an APP for the phone An application that will link all the components AI services and big data analytics (as a separate product) The timeline 2-3 years, potentially 4 for completion This is to move what we are doing manually at the moment (and what we are planning to do) to something that is … -
best way to handle websocket jwt authetication using django channels for backend and android kotlin?
I have learned how to make a simple chat app with Django channels and android with Kotlin. I'm using rest framework in Django. What is the best way to handle authentication in both platforms? I couldn't find anything useful in the internet. -
what is a 'no such table' error in Django for creating a register page?
I'm trying to create a registration page. I'm getting this error the views.py: def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: print("momooo!") user = User.objects.create_user(username, email, password) print(("more mooomoo")) user.save() except IntegrityError: return render(request, "auctions/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/register.html") the register.html page: {% extends "auctions/layout.html" %} {% block body %} <h2>Register</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="Email Address"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <div class="form-group"> … -
How do I get the value from the field in a one-to-one relationship tabularinline
How do I get the value from the field in a one-to-one relationship. The tables Ojbects and Object_Info are linked using TabularInline. And I want to get a value from a field by OneToOneField relationship. How to do it with signals. In this case I'm using post_save. I get an error. class Ojbects(models.Model): title = models.CharField(max_length=10) class ServerInfo(models.Model): data = models.TextField() object = models.OneToOneField(Ojbects, on_delete=models.CASCADE, related_name="data") @receiver(post_save, sender = Ojbects) def create(instance, sender, **kwargs): print(instance.data) -
Django structure with directories don't load views
I'm coming from the larvae on Django and I have a problem on this side and I can't say 100% of the documentation that I understand exactly the structure. Do I have to make a directory for each part of the application, for example? For example for the user a special directory, for the management of the application another one and so on? Or can I have a main application like I did acm and have in it a folder view with several views.py and import them in urls? Because I can't do that, I get an error. For example this is my structure structure This is the error AttributeError: module 'main.views' has no attribute 'pages_views' Url function from main from django.contrib import admin from django.urls import path from django.urls import include from rest_framework_jwt.views import obtain_jwt_token from . import views urlpatterns = [ path('', views.pages_views.index, name='index'), ] AttributeError: module 'main.views' has no attribute 'pages_views' And url acces from project_management (core app I think) from django.contrib import admin from django.urls import path from django.urls import include from rest_framework_jwt.views import obtain_jwt_token from . import views urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls) ] -
How can upload word or pdf file in django
I am trying to upload word/pdf file but it's not working. My form submit successfully but file not store in document field. It show empty field and it also not show any error during submit the form, i don't know where is the issue and how can i fix the issue. I add the MEDIA URL in setting and also define the path in urls View.py class SaloonRegistration(TemplateView): template_name = 'saloonRegistration.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): saloon = SaloonRegister( saloon_name=self.request.POST.get('saloon_name'), owner_name=self.request.POST.get('owner_name'), address=self.request.POST.get('address'), contact_no=self.request.POST.get('contact_no'), document=self.request.POST.get('document') ) saloon.save() return redirect('menu') Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() document = models.FileField(upload_to='doc/') is_active = models.BooleanField(default=False) Template {% extends 'home.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="saloon_name">Saloon Name <input type="text" name="saloon_name" placeholder="Enter Your first name"> </label> <label for="owner_name">Owner Name <input type="text" name="owner_name" placeholder="Enter Your last_name"> </label> <label for="address">Address <input type="text" name="address" placeholder="Enter email address"> </label> <label for="contact_no">Contact No <input type="number" name="contact_no" placeholder="Enter your username"> </label> <label for="document"> upload Doc <input type="file" name="document" id="document"> </label> <button type="submit">Submit</button> </form> {% endblock%} -
django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint
I'm trying to get a session_key from my React app (front-end) where Django-rest-framework is used for Backend. But it shows server error. Views.py: @api_view(['GET']) def addToCartForSession(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) urls.py: path('addToCartForSession/<str:pk>/', views.addToCartForSession, name='addToCartForSession'), When I go to this url directly from browser search bar, it works fine. But if I call this function(addToCartForSession) from my React app, it shows server error like this: django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint DETAIL: Failing row contains (54, null, null) in React: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCartForSession/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrftoken } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } So, How can I get a session_key from front-end with drf? -
request cart_obj in template tag filter Django
Is it possible to add a cart_obj request in a Django Template filter I currently have in my template tag: @register.filter def existing_product(product): return CartItem.objects.filter(item_id=product.id).exists() and in my template: {% if product|existing_product %} {% endif %} the only problem is that this filter only finds the item_id that is equal to the product.id , I want to be able to add an additional filter that looks for the item_id in the cart_obj. views.py cart_obj, new_obj = Cart.objects.new_or_get(request) basically my template tag would be something like: return CartItem.objects.filter(item_id=product.id, items_cart_id=cart_obj).exists() with the addition of filtering the 'items_cart_id', but I'm not sure how to do this and what to put in the template 'if' condition. Any ideas? Thanks -
How to call the value of a key in JavaScript?
I am learning Django. I have an app name quizes In the models.py section I have this: from django.db import models DIFFICULTY_CHOICES = ( (1, 'easy'), (2, 'intermediate'), (3, 'difficult') ) class Quiz(models.Model): difficulty = models.IntegerField(choices=DIFFICULTY_CHOICES) This is how views.py looks like: from django.shortcuts import render from .models import Quiz from django.views.generic import ListView class QuizListView(ListView): model = Quiz template_name = 'quizes/main.html' def quiz_view(request, pk): quiz = Quiz.objects.get(pk=pk) return render(request, 'quizes/quiz.html', {'obj': quiz}) Now in the main.html I have a button that calls these values and it looks like this: <button type="button" class="btn btn-primary modal-button" data-difficulty="{{obj.difficulty}}" data-bs-toggle="modal" data-bs-target="#quizStartModal"> {{obj.name}} </button> When the user clicks on the button, I would like to display the value of the key in difficulty. the key is fetched by the button using the data-difficulty method. In the JavaScript part, this is what I am doing: const modalBtns = [...document.getElementsByClassName("modal-button")] const modalBody = document.getElementById("modal-body-confirm") modalBtns.forEach(modalBtn=> modalBtn.addEventListener('click', ()=>{ const difficulty = modalBtn.getAttribute('data-difficulty') modalBody.innerHTML = ` <div> difficulty: <b>${difficulty} </div> ` So I am getting the output as 1 for easy, 2 for intermediate and so on. But I want to output the value of those keys instead of those keys themselves. How do I do that?