Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get plain value of Foreign Key
I have the following model: def MyModel(models.Model): other = models.ForeignKey(OtherModel, db_column='other', on_delete=models.DO_NOTHING, db_constraint=False, blank=True, null=True) The problem is that maybe a value in other field (which is a string value) of the model MyModel could not be in OtherModel so when I do, for example: inst = MyModel.objects.first() # Gets any (with an "invalid" key in other) inst.other It threw: others.models.OtherModel.DoesNotExist: OtherModel matching query does not exist. I'd like that, in case that it doesn't exists, get the plain value of the other field. How could I achieve that? Any kind of help would be really appreciated -
'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' error in ManyToMany field with 'self'
This is related to this question, I thought it makes sense if I open a separate question for this specific issue. I'd like to link to each other more instances of the same model: class MsTune(models.Model): concordances = models.ManyToManyField('MsTune', through='Concordance', blank=True) [...] class Concordance(models.Model): tune = models.ManyToManyField(MsTune) title = models.CharField(max_length=64) def __str__(self): return self.title What I want is to link together many similar tunes, and get the list of the other-similar tunes for each tune. E.g: tune_1: concordances.all: tune_1a, tune_1b tune_1a: concordances.all: tune_1, tune_1b tune_1b: concordances.all: tune_1, tune_1a Now, when I access concordances.all from my template I get a 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' error. Accessing concordance_set, on the other hand, gives me only the id/name of the concordance instance (the through model), and I'm not able to get information about the single tunes with, for example, {% for concordance in tune.concordance_set.all %} {{ concordance.tune }}{% endfor %}. That is 'None', or empty. What am I overlooking? -
git working/production branch for django project
What is the right workflow for a "working" and "production" branch in github (concerning a django project)? To be specific: I have obviously settings.py and wsgi.py file in production that are different from the ones in working which I use locally. So I considered adding these files to .gitignore, but thats obviously not going to work when two+ people work on it. And pushing "working" to "production" every now and then will overwrite these files there. And just cheking out "production" on the server will either give a warning message or overwrite settings... Surely others have a solution, but its not obvious to me... Can anyone help? (I am very new to git, I have to google every command... more or less...) -
django rest framework not outputting custom responses
whenever I post a valid request to create view I get { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" } instead of the custom responses I setup class ServerView(generics.CreateAPIView): queryset = Server.objects.all() serializer_class = ServerSerializer class CreateView(APIView): serializers_class = CreateSerializers def post(self, request, format=None): serializer = self.serializers_class(data=request.data) if serializer.is_valid(): name = serializer.data.get(name) queryset = Server.objects.filter(name=name) if not queryset.exists(): server = Server(name=name) server.save() return Response(ServerSerializer(server).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Join or try another name'}, status=status.HTTP_226_IM_USED) return Response({'Bad Request': 'Name is not valid'}, status=status.HTTP_400_BAD_REQUEST)``` -
Testing a CreateView with TestCase in Django
I'm new to unit testing in Django and I'm trying to test my CreateView which creates a new blog post when is submited, my first assertEquals which checks if the response code is 302 which practically means that the form was submited correctly because it was redirected is ok but the second check it gives me this error: " Traceback (most recent call last): File "/Users/aryanlilian/Desktop/EcoMon/blog/tests/test_views.py", line 53, in test_post_create_view_POST self.assertEquals(post.title, 'test post') AssertionError: 'Test post' != 'test post' Test post ? ^ test post ? ^ " my TestCase from django.test import TestCase, Client from django.urls import reverse from blog.models import Post, Comment from users.models import User class TestViews(TestCase): def setUp(self): self.client = Client() self.blog_url = reverse('blog') self.tag_url = reverse('tag', args=['test']) self.post_url = reverse('post', args=['test-post']) self.add_post_url = reverse('add-post') self.user = User.objects.create( username='testuser', email='test@test.com', first_name='test', last_name='test', password='test' ) self.post = Post.objects.create( author=self.user, title='Test post', content='test content post', ) self.post.tags.add('test') def test_blog_list_view_GET(self): response = self.client.get(self.blog_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/blog.html') def test_tagged_post_list_view_GET(self): response = self.client.get(self.tag_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/blog.html') def test_post_detail_view(self): response = self.client.get(self.post_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/post.html') def test_post_create_view_POST(self): response = self.client.post(self.add_post_url, { 'title': 'test post', 'content' : 'test content', 'category' : 'BUSSINESS', 'tags' : 'test' }) post = Post.objects.last() self.assertEquals(response.status_code, … -
Django Rest - Authorization Data Filtering
When i login, i only want see data that is connected to my own account. With every model there is an id. But i can't figure out how to do that. I have these models. This is for a new project i am working on. It is for a SAAS software. class ServicesModel(models.Model): id = models.UUIDField( primary_key=True, auto_created=True, unique=True, default=uuid4, editable=False) saloon_id = models.CharField(max_length=25) service_name = models.CharField(max_length=30) service_price = models.IntegerField() service_price_readable = models.CharField() service_explanation = models.CharField(max_length=150) service_length = models.IntegerField() service_length_readable = models.CharField() created_at = models.DateField(auto_now_add=True, auto_created=True) updated_at = models.DateTimeField(auto_now=True) class SaloonsModel(models.model): id = models.UUIDField( primary_key=True, auto_created=True, unique=True, default=uuid4, editable=False) subscription = models.IntegerField(null=False) subscription_active = models.BooleanField(null=False) transactions = ArrayField(models.OneToOneField()) payment_method = models.CharField(max_length=25) last_payment = models.DateField(null=True) saloon_name = models.CharField(max_length=50) saloon_password = models.CharField(max_length=100) saloon_phonenumber = models.CharField(max_length=15) saloon_email = models.CharField(max_length=75) saloon_bio = models.TextField(max_length=350) saloon_employees = models.OneToOneField(EmployeesModel) available_times = ArrayField(models.DateTimeField(null=True)) services = models.OneToOneField(ServicesModel) created_at = models.DateField(auto_now_add=True, auto_created=True) updated_at = models.DateTimeField(auto_now=True) class LoginSessionsModel(models.Model): id = models.UUIDField( primary_key=True, auto_created=True, unique=True, default=uuid4, editable=False) ip_adress = models.CharField(max_length=15, null=False) saloon_id = models.OneToOneField(SaloonsModel) created_at = models.DateTimeField(auto_now_add=True, null=False) -
Requesting a specific view in Django multitenant API
Created a multitenant API in Django 2.2.17 using django-tenant-schemas==1.10.0 and currently testing it using Postman. I'm able to create a new organization (which is the Tenant) and GET them all Thing is, in the GET and POST requests to the endpoint http://127.0.0.1:8000/employee/ I'm getting AttributeError at /employee/ 'str' object has no attribute 'get' Here's my employee/views.py from django.shortcuts import render from employee.models import Employee from organization.models import Organization from django.http import JsonResponse,request, HttpResponse from django.views import View from tenant_schemas.utils import schema_context import json # Create your views here. class EmployeeView(View): def get(self, request, *args, **kwargs): try: organizations = Organization.objects.get(domain_url=request.META['HTTP_HOST']) schema_name = organizations["schema_name"] #schema_name = organizations.schema_name except Organization.DoesNotExist: return "no organization" with schema_context(schema_name): employees = Employee.objects.all() data = {"results": list(employees.values("id","name"))} return JsonResponse(data) def post(self, request, *args, **kwargs): try: organizations = Organization.objects.get(domain_url=request.META['HTTP_HOST']) schema_name = organizations.schema_name except Organization.DoesNotExist: return "no organization" with schema_context(schema_name): name = json.loads(request.body)['name'] employee = Employee(name=name) employee.save() return "Employee added successfully" -
Matplotlib Live Animation in Django
I am trying to display a live graph constructed with matplotlib's animation feature in Django, however I am stuck and do not know how to approach this. I have successfully generated the animation using matplotlibs FuncAnimation. Therefore, I have an matplotlib object called "animation" that updates with live data. Now my question is, how to I dynamically show this animation object in my web page using Django. I am really struggling with this. If someone has advice, it would be greatly appreciated. -
CSS Not loading in Django-Oscar production but in development
:8000 CSS loading in development but NOT in production -
Password fields attribute not rendering correctly registration page Django
I'm creating a registration page in Django and everything works fine, and gets rendered correctly except the password fields. Why can that due to? I've tried building a form without the inbuild Django methods but it doesn't work either. It is very weird as I think all the code is working fine and everything is build correctly. Here is the html: <body class="bg-gradient-primary"> <div class="container"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-5 d-none d-lg-block bg-register-image"></div> <div class="col-lg-7"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1> </div> <form class="user" method="POST"> {% csrf_token %} <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> {{ form.first_name }} </div> <div class="col-sm-6"> {{ form.last_name }} </div> </div> <div class="form-group"> {{ form.email }} </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> {{ form.password1 }} </div> <div class="col-sm-6"> {{ form.password2 }} </div> </div> <button type="submit" class="btn btn-primary btn-user btn-block"> Register Account </button> <hr> <a href="index.html" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Register with Google </a> <a href="index.html" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Register with Facebook </a> </form> <hr> <div class="text-center"> <a class="small" href="forgot-password.html">Forgot Password?</a> </div> <div class="text-center"> <a class="small" … -
How to get each column as one list from a Django QuerySet over DRF
Using Django-REST-framework, I have the following view: class MyRESTfulAPIView(APIView): permission_classes = [IsAuthenticated, MyCustomPermision] def get(self, request): data = MyModel.objects.values('field1').annotate(field2=..., field3=...) return Response(data) Which returns a JSON with the shape: [ {'field1': Result1.field1, 'field2': Result1.field2, 'field3': Result1.field3}, {'field1': Result2.field1, 'field2': Result2.field2, 'field3': Result2.field3}, ... ] Is there a way to get each column as a list of values, like this: { 'field1': [Result1.field1, Result2.field1, ...], 'field2': [Result1.field2, Result2.field2, ...], 'field3': [Result1.field3, Result2.field3, ...], } The exact shape of the JSON is not important, just getting each "column" (model field) as one list of all values, instead of each row as a dictionary. (Because the data then gets passed to a library that expects the data to be in separate lists) Obviously I could just unpack the QuerySet and restructure it with Python, but I am looking for some way to tell either Django or DRF to build the JSON like that in the first place instead having it build it one way and then iterate over it again to restructure it. -
Trying to render data from database with a model in Django but it's showing operationError
Inside product app in views.py ''' from django.shortcuts import render from .models import Person def product_details(request,*args, **kwargs): obj=Person.objects.get(id=1) context={ 'object': obj } return render(request, "productH/detail.html", context) ''' Inside Templete I've made a new folder 'productH', and inside productH I made detail.html Inside detail.html ''' {% extends 'base.html' %} {% block content %} <h1> {{object.title}} </h1> <p> this is showing detail.html file </p> {% endblock %} ''' after this in url.py I've added ''' from Products.view import import person url={ path('product/', product_details) ''' inside model I've coded ''' [from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30) roll_no = models.DecimalField(max_digits=3, decimal_places=0) total_marks = models.DecimalField(max_digits=4, decimal_places=2) ''' this Error is occuring. -
How can I pass my function inside my class model as a field?
I'm using the 3rd party library, Django Extensions, specifically for AutoSlugField(). I want to implement their use of RandomCharField() in my model for my slug field. from django_extensions.db.fields import AutoSlugField, RandomCharField class Post(models.Model): class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() ... #unique_string = RandomCharField(length=10, unique=True) slug = AutoSlugField(populate_from = models.random_string(), blank=True) ... objects = models.Manager() bucketobjects = BucketObjects() def random_string(self): unique_characters = RandomCharField(length=10, unique=True) self.slug = unique_characters self.save() def __unicode__(self): return self.stock_list AutoSlugField requires the populate_from parameter. Passing RandomCharField() like so: slug = AutoSlugField(populate_from = RandomCharField(), ...) Does not work: TypeError: 'populate_from' must be str or list[str] or tuple[str], found <django_extensions.db.fields.RandomCharField> So instead I want to make a function within my class that creates and saves a RandomCharField to my slug field. In the model above, you can see I commented out unique_string, if I pass that field to my populate_from parameter, then everything works fine. But it seems a redundant and a waste of space to have two model fields that are exactly the same. How can I pass my random_string function to my slug populate_from parameter whenever a Post is created? Thank you for the help. -
Reload a bootstrap toast
I have a bootstrap toast to inform user a successful form submission with Ajax. Message is generated in Django view. How Can i reload the toast to show New messages? I tried to reload the entire div but the data-delay doesn't work anymore. -
How to control developers so that only part of modules are assigned to them?
I have a question, what is the best way to control the code to developers? I have a project in development with 5 people, who work collaboratively (Git), but I don't want everyone to see the complete code, if not only one person has control and the others only the parts / modules assigned to them. In the project we use VSCode, Django, with Git. -
django template filter throws decimal.InvalidOperation although the exception is handled
From the server log, decimal.InvalidOperation exception is thrown: "......django/template/defaultfilters.py", line 138, in floatformat d = Decimal(input_val) decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] But the InvalidOperation is actually handled in the django floatformat filter: try: input_val = repr(text) d = Decimal(input_val) except UnicodeEncodeError: return '' except InvalidOperation: if input_val in special_floats: return input_val try: d = Decimal(force_text(float(text))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): return '' I cannot duplicate the situation, but can see that the error is thrown on server all the time. It happens after upgrading python from 3.7 to 3.9, django version unchanged. Any idea why the floatformat template filter would throw an already handled exception? Thanks. -
How to access the Django app running inside the Docker container?
I am currently running my django app inside the docker container by using the below command docker-compose run app sh -c "python manage.py runserver" but I am not able to access the app with local host url, (not using any additional db server or ngnix or gunicorn, just simply running the django devlopment server inside the docker). please let me know how to access the app -
Field 'Product_id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x0000022D29594848>'
Hello trying to save data and display it on my cart using django. Its giving me an value error when i try to add a product to cart. The error message is: Field 'Product_id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x0000022D29594848>'. here is my cart file source code: from decimal import Decimal from django.conf import settings from store.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(Product_id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.Product_id)]['product'] = product for item in cart.values(): item['Price'] = Decimal(item['Price']) item['total_price'] = item['Price'] * item['Quantity'] yield item def __len__(self): """ Count all items in the cart. """ return sum(item['Quantity'] for item in self.cart.values()) def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.Product_id) if product_id not in self.cart: self.cart[product_id] = {'quantity': … -
How to clean up downloaded files in Django view testing?
I have a Django view that returns a file to download (response['Content-Disposition'] = 'attachment; filename=' + filename) in response to a POST as the contents of the file are dependent on data submitted by a form. In setting up my tests for this view, I'm having a hard time finding a clean way to download the file and make sure it is cleaned up afterwards as this doesn't come for free with the TestCase behavior. Currently I have the following: with tempfile.TemporaryDirectory(dir='.') as temp_dir: os.chdir(temp_dir) response = self.client.post(...) # Do asserts of the downloaded file/response object here os.chdir('..') This has the benefit of creating a temporary directory where the file is downloaded to, and the whole directory is deleted when the test completes. Also, if any of the asserts fail the temp directory (and contents) will stick around, but this specifically feels fragile and like it could break other tests because of the directory change. Is there a better way/pattern to accomplish this? -
Django Website <button /> tags do not work on firefox web browser
I have created a read more js event for my django app. To fire the event there is a button with onclick="myFunction()" in the button tag of the html. The issue I am having is on Firefox. I can't click any buttons or any links on the django app/website. AT ALL. This is only the case for my django app, other website works perfectly. When clicking the button nothing comes up in the console. It is almost as if the browser doesnt even see the button or any menu links. Safari and Chrome everything works normally. Thank you for your time and responses! -
Django - De-compose bcrypt hashed password
I want Django to use the Bcrypt algorithm to hash my password. The result looks like this: bcrypt_sha256$$2b$12$JWIEqA1.FnHvaymy2vrGcexFbglZ4qdTlJ9fFNTbAy87VYvwmNwYa Django says that the password is stored in the form of: <algorithm>$<iterations>$<salt>$<hash> But it does not really seem consistent with the result. I need to get the salt from the previous result, do you know wich part it is ? Thank you. -
Output query result into table in Django
I currently have PHP scripts that run a query against a MySQL database and display the results in a table. I want to be able to replicate this in Django, but I am having difficulty in outputting the row data. I would eventually like to use Datatables to output the results, however I am having difficulty getting the results in just a basic table. Most of the MySQL queries are not straight-forward and involve various joins, subqueries, calculations etc and I'm confused on how to have this complexity in Django. Is is easier to use connection to send raw SQL? #models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') author_id = models.ForeignKey(Author, on_delete=models.CASCADE) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) #views.py from django.shortcuts import render from .models import Question def index(request): row_data = Question.objects.values('question_text', 'pub_date', 'author__name', 'author__email', 'choice__votes') context = {'row_data': row_data} return render(request, 'datatable/index.html', context) #templates/datatable/index.html {% if row_data %} <table> <tr> <th> Question text </th> <th> Pub date </th> <th> Author name </th> <th> Email </th> <th> Votes </th> </tr> {% for question in row_data %} <tr> <td>{{ question.question_text }}</td> … -
Error retrieving access token: b'{\n "error": "redirect_uri_mismatch",\n "error_description": "Bad Request"\n}'
Trying to authenticate from Nuxt App using Django rest + allauth + dj-rest-auth First Error allauth.socialaccount.models.SocialApp.DoesNotExist: SocialApp matching query does not exist. resolved this by changing SITE_ID = 1 TO 2 Second I am getting This error Traceback (most recent call last): File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\views.py", line 48, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\views.py", line 138, in post self.serializer.is_valid(raise_exception=True) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\serializers.py", line 422, in run_validation value = self.validate(value) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\registration\serializers.py", line 117, in validate token = client.get_access_token(code) File "C:\Users\xyz\django-env\lib\site-packages\allauth\socialaccount\providers\oauth2\client.py", line 91, in get_access_token raise OAuth2Error("Error retrieving access token: … -
change django view context based on template
I'm wondering if there is a way to change django view context based on template (I've no idea if it's possible) I'm building a chat application where I loop through all the thread messages and I'm looping through all images that if the image message id equals to message id to show the message related image. It's something like this .. {% for message in chatmessages %} <p>{{ message.message }}</p> {% for img in images %} {% if img.message.id == message.id %} <img src="{{ img.image.url }}"> {% endif %} {% endfor %} {% endfor %} and the same for attachments. I'm sending these context from my view context = { "me": me, "threads": threads, "other_user": other_user, "chatmessages": ChatMessage.objects.filter(thread=thread.id), "images": MultipleImage.objects.all(), "attachments": MultipleAttchment.objects.all(), } Any better way to reduce my looping in template for a better functionality. here is my models.py ... class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) voice = models.FileField(upload_to=upload_voice_dir, blank=True, null=True) class MultipleImage(models.Model): message = models.ForeignKey('ChatMessage', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_img_dir, blank=True, null=True) class MultipleAttchment(models.Model): message = models.ForeignKey(ChatMessage, on_delete=models.CASCADE) attachment = models.FileField(upload_to=upload_att_dir, blank=True, null=True) ... looking for a better way :( -
how to change innerHTML using classname inside loop
here my code i just wanna change the innerHTML of btn by grabbing classname which is inside for loop {% for pbyid in productbyid %} <div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'> <div> <div> <a href="/viewpage/{{pbyid.id}}"><div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div></a> <span class="top-left">{{pbyid.discountpercentage}}% off</span> </div> <div class="card-body"> <h5 class="card-title cardtitle">{{pbyid.title}}</h5> <div><p class="carddesccrip">{{pbyid.desc}} </p></div> <div class='pricce_card'> <span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span> <span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span> </div> </div> <div class="card-body"> {% comment %} /viewpage/{{pbyid.id}} {% endcomment %} <p href="" id='' class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction({{pbyid.id}})" > Add to cart <i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></p> </div> </div> </div> {% endfor %} js how can i change html of btn from class , when i try it doesn't wok with classname but it work with id , but for id is specific so we have to use classname but i'm not exactly getting how to solve can anyone have idea to solve it function myFunction(id) { var x = document.getElementsByClassName("caddtocart"); x.innerHTML = "added"; console.log(id); } </script>