Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to format (succinctly) a date when returning django validation?
For a string type foo, you can write print('The value is %s' % foo) But how do you do this if foo is a datetime? from datetime import date foo = date.today() print('The value is %?' % foo) i.e. what do you write in place of ? to format as a date; preferably dd-mmm-yyyy say? Here is what I'm really trying to do. In django, I'm validating a date: if start_date < date.today(): raise ValidationError( _('%(start_date)s must be on or after today.'), params={'start_date': start_date}, ) But I need something better than s -
django - get first record for each day
I have a model Sales with: Saler Product sold Date I would like to get the first sale for each date and for each saler, how can I do that? Thanks -
Handle IntegrityError on signup for allauth Django
I'm using Django allauth for google user signup and login. Now I wanted to have unique email address for each user that tries to signup be it through google or normal django signup. For unique email I wrote the following in models.py User._meta.get_field('email')._unique = True this is working perfectly fine but the issue arises when signing up through google login. settings.py 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_filters', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] I just want to handle the exception. Thanks in advance -
Gunicorn - ModuleNotFound crispy_forms (But is installed)
I am trying to setup Crispy Forms on my Django environment. I have installed Crispy Forms using pip3 install --user django_crispy_forms and I have added the 'crispy_forms' to the INSTALLED APPS within my settings.py file. Although, I am unable to boot up my gunicorn service file, as an error is displaying "ModuleNotFound Error crispy_forms" Just to ensure that Crispy Forms is installed, I tried to rerun the installation to which I receive a message "requirements are already satisfied". Any ideas to what could be causing this behaviour? Edit: If I remove 'crispy_forms' from the INSTALLED APPS area, my gunicorn service boots up perfectly fine. Thanks! -
Django + Bootstrap collapsed table front-end issue?
I have been trying to figure out a front-end issue I've been on for a few days. I am using Django + Bootstrap collapsed accordion. What I am trying to do is completely hide a div, and all spacing until the collapsable button is clicked (eyeball). For some reason it's throwing a couple weird front-end issues like below. Basically what the collapsed div does, is show details if the user provides them which are new table rows. But on page load it shows all of this extra spacing where the collapsed rows are, and also throws some odd border issues? The first entry with the issue is an instance where a user has provided Address Phone Position Concern This is the HTML I have in place as of now, <style> .hiddenRow { border-top-style: hidden; border-bottom-style: hidden; } </style> <div class="table-responsive"> <table class="table small"> <thead> <tr> <th></th> <th>Entry Date</th> <th>Employee First Name</th> <th>Employee Last Name</th> </tr> </thead> {% for employee_entry in employee_entries %} <tbody> <tr data-toggle="collapse" class="accordion-toggle" data-target=".employee-entry-{{ employee_entry.id }}"> <td><button><span class="glyphicon glyphicon-eye-open"></span></button></td> <td>{{ employee_entry.created_at|date:'M d, Y' }}</td> {% if employee_entry.first_name %} <td>{{ employee_entry.first_name }}</td> {% else %} <td></td> {% endif %} {% if employee_entry.last_name %} <td>{{ employee_entry.last_name }}</td> {% else … -
Unable to Migration Django models
I am having the issue on unable to migrate models on Django. It has worked for the first time and then again I tried on the next project folder and it has never worked for me. -
How to test image upload on Django Rest Framework
i'm on a struggle. The problem is with the unit testing ("test.py"), and i figured out how to upload images with tempfile and PIL, but those temporary images never get deleted. I think about making a temporary dir and then, with os.remove, delete that temp_dir, but the images upload on different media directorys dependings on the model, so i really don't know how to post temp_images and then delete them. This is my models.py class Noticia(models.Model): ... img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg") ... test.py def temporary_image(): import tempfile from PIL import Image image = Image.new('RGB', (100, 100)) tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg', prefix="test_img_") image.save(tmp_file, 'jpeg') tmp_file.seek(0) return tmp_file class NoticiaTest(APITestCase): def setUp(self): ... url = reverse('api:noticia-create') data = {'usuario': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()} response = client.post(url, data,format="multipart") ... So, to summarize, the question is, ¿How can i delete a temporary file from different directories, taking into account that those files strictly have to be upload on those directorys? -
Django ecommerce: Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<product_id>[0-9]+)/$']
This is my first ecommerce web-site with django and it's a little tough to wrap my head around all the routing and cart function, and I fixed lots of stuff, but I just can't fix this error. I tried doing some stuff in urls but it just didn't work out. onlineshop/models.py: from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('onlineshop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey( Category, related_name='product', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug')) def __str__(self): return self.name def get_absolute_url(self): return reverse('onlineshop:product_detail', args=[self.id, self.slug]) onlineshop/views.py: from django.shortcuts import render, get_object_or_404 from .models import * from cart.forms import CartAddProductForm def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) context = { 'categories': categories, 'category': category, 'products': products, } return render(request, 'onlineshop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, … -
Django and Ajax. js not running
I hope anyone can help me with my code. I have here this html that was a js function with the goal that, whenever someone changes the "filament" option, it will change the "colors" available options available in the select: <form method="post" enctype="multipart/form-data" style="max-width: 1000px;"> {% csrf_token %} {{ form.as_p }} {% for message in messages %} <div class="alert alert-success"> <a class="close" href="#" data-dismiss="alert">×</a> {{ message }} </div> {% endfor %} <h2 class="sr-only">Login Form</h2> <div class="illustration"> <div class="form-group"> <input type="file" name="printingfile"/ style="font-size: medium;"> <select class="form-select" aria-label="Default select example" id="=filament"> <option value="1">PLA</option> <option value="2">ABS</option></select> <select class="form-select" aria-label="Default select example" id="=color"></select> <button class="btn btn-primary btn-block" type="submit">Submit</button></div> </div> </form> </section> <div></div> <script src="{% static 'assets/js/jquery.min.js'%}"></script> <script src="{% static 'assets/bootstrap/js/bootstrap.min.js'%}"></script> <script src="{% static 'assets/js/Animated-Text-Background.js'%}"></script> <script src="{% static 'assets/js/Cookie-bar-footer-popup.js'%}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% block javascript %} <script> //updating the colors available $("#filament").change(function () { var filament = $(this).val(); var color = $('#color'); console.log(filament); $.ajax({ url: '/get_colors/', data: { 'filament': filament }, dataType: 'json', success: function (data) { color.empty(); for (var i = 0; i < data.lenght; i++) { color.append('<option value=' + data[i].name + '>' + data[i].name + '</option>'); } } }); }); </script> {% endblock javascript %} </body> </html> This calls a view in Django. I … -
how to use a singleton instance in multiple django apps
I'm creating a website using django framework. I am using a singleton in one django application and I use it to store some variables . Now that I have created another app in my project, how can I import the data from my singleton to the new app. class SingleInstanceMetaClass(type): def __init__(self, name, bases, dic): self.__single_instance = None super().__init__(name, bases, dic) def __call__(cls, *args, **kwargs): if cls.__single_instance: return cls.__single_instance single_obj = cls.__new__(cls) single_obj.__init__(*args, **kwargs) cls.__single_instance = single_obj return single_obj class MyClass(metaclass=SingleInstanceMetaClass): def __init__(self): self.df = None self.del_var = None self.quali_col = None self.quanti_col = None self.target_var = None self.date_col = None And this what my project looks like without the other django files(models,urls,...) Project Description -views.py Transformation -views.py -
Handling complex computation on a web app involving data from a database
Just some background. This question is to help my team and I make a decision on how to handle an app we are working on. Currently the application is hosted locally in ASP.NET C# and the complex calculations that are done are handled in SQL as a stored procedure. The data is pulled into queries and the server will handle all the calculations and return a recordset which is written to a table and the front end can access that table. So moving forward, we're thinking of moving the application to the web with Django and deciding how to handle the server side of things. So what we really wanted to understand is, how do others handle situations like these? Do we continue with the same idea and build a SQL server and do the same thing or is there a better way to solve this problem? We want to the user to be able to kick the calculations off and do other things while it runs in the background. The user shouldn't have to sit on the page because these calculation can take an hour or more depending on the complexity. We'd appreciate the thought and ideas. Thank you … -
django django-yearmonth-widget display month as month name
I have used package "django-yearmonth-widget" to have year and month selection and not complete date. Here, day is fixed i.e. 1st of every month. This implementation is working fine. Problem i am facing is below How to display month as month name and not number display Option 0 as --Year-- and --Month-- or something like --Select-- Give proper label to the field Please refer below screenshots for reference -
SMTPAuthenticationError: Authentication unsuccessful [BL1PR13CA0128.namprd13.prod.outlook.com] in Django
i'm trying to send and email (from my personal hotmail account) from a Django API. When i make a request through Postman to the local server it works but when i host my app on Heroku it raise the following exception: I've reading and Hotmail accounts have something like SMTP permissions: Here is my Django config vars: CORS_ALLOWED_ORIGINS = ['https://gianlop3z-dev.web.app'] EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER') django_heroku.settings(locals()) The environment variables are in Heroku. -
Why doesn't {% if %} {% else %} construction work in Django template?
So I am trying to display "YOU" above the comment if it's in fact a comment that has been posted by current user, otherwise I am trying to display just a username of one who left a comment. But somehow if/else doesn't work. Can anyone please tell me what am I doing wrong? Thank you beforehand! my models.py class Comments(models.Model): commented_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.TextField(max_length=300) def __str__(self): return self.comment my forms.py class CommentForm(forms.ModelForm): class Meta: model = Comments fields = ['comment'] widgets = {'comment': forms.Textarea(attrs={'class': 'form-control', 'rows': 5})} my views.py class Comment(CreateView, LoginRequiredMixin): form_class = CommentForm template_name = 'app/comments.html' login_url = 'login' success_url = reverse_lazy('comments') def form_valid(self, form): self.object = form.save(commit=False) self.object.commented_by = self.request.user self.object.save() if self.object: messages.success(self.request, 'Success') else: messages.error(self.request, 'Error') return redirect(self.get_success_url()) def get_initial(self): initial = super().get_initial() initial['comment'] = 'Please leave your comment here' return initial def get_context_data(self, **kwargs): context = super().get_context_data() context['comments'] = Comments.objects.all() return context and my condition from the template: <div> <div class="commentsContainer"> {% for comment in comments %} {% if comment.commented_by == user.username %} <h4>YOU</h4> {% else %} {{comment.commented_by}} {% endif %} <div class="comment"> {{comment}} </div> {% endfor %} </div> -
Redis wrong version number
I am very new to deploying my Django site on Heroku. I was trying to get Celery to work (as my Django has long processes). I was following a tutorial on how to set up Redis on Heroku. The issue now is that I am getting this error: Error accepting a client connection: error:1408F10B:SSL routines:ssl3_get_record:wrong version number (conn: fd=11) There are not many solutions online, I only kind of understand that I will need to downgrade this somehow, any suggestions on how to overcome this problem? Note that I am using the free tier for Heroku and Redis. -
Django Abstract User - how to implement it and adapt to current signal
I don't have the standard Django User model to rely on, I don't know how to refer to the instance below. Before changing to the Abstract User Model I would refer to (user=instance). I was attempting to adapt a functioning e-commerce site by removing/including aspects, one of these adaptations was a Custom User model. Could it be true that I wouldn't need the "create_or_update_user_profile" function anymore since User is now the model that is used as the AUTH_USER_MODEL? When attempting to log in as admin, this error fires: File "/workspace/Project-Saasy/profiles/models.py", line 48, in create_or_update_user_profile instance.userprofile.save() AttributeError: 'User' object has no attribute 'userprofile' So I wondering either how to add the attribute to the 'User' object, or if there another way around all of this models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.conf import settings from django.dispatch import receiver class User(AbstractUser): """ A user profile model for maintaining default delivery information and order history """ is_volunteer = models.BooleanField(default=False) is_organisation = models.BooleanField(default=False) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_street_address2 = models.CharField(max_length=80, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_county = models.CharField(max_length=80, null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) class Volunteer(models.Model): user … -
How to get last element in a ForeignKey relation?
To describe my problem I will use basic models : class Chatroom(Model): date_created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=3000) class Message(Model): date_created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=3000) room = models.ForeignKey( Chatroom, on_delete=models.CASCADE, related_name='messages' ) I want to display every last messages sent to a room ordered by date of creation. In practice, the user connect to the page and he can see the messages ordered by date, but only the last message of each room. Example : in the database we have: rooms = [RoomA, RoomB] messages = [ { text: 'firstA', date_created: 01/05/21, room: RoomA }, { text: 'secondA', date_created: 03/05/21, room: RoomA }, { text: 'firstB', date_created: 02/05/21, room: RoomB }, { text: 'secondB', date_created: 06/05/21, room: RoomB }, ] As a result of my queryset, I want to get last messages of each room, meaning messages [secondB, secondA]. Currently I am doing the following : messages_uids = Message.objects \ .order_by('room_id') \ .distinct('room_id') \ .values_list('pk', flat=True) queryset = Message.objects \ .filter(pk__in=messages_uids) \ .order_by('-date_created') return queryset I have only one message per room (good point), messages are ordered by date_created (good point), but I do not have the last message of each room. With the previous set of example, I … -
DisabledBackend Error with every second reload with Django, Celery and RabbitMQ
I am using django, celery and RabbitMQ for a webserver. On my development server everything works fine. However, when I try to run the webserver on my production server with apache2/mod_wsgi every second time I reload the result page I get the following error: 'DisabledBackend' object has no attribute '_get_task_meta_for' That happens when I try to run the following command: task_state = <taskname>.AsyncResult(task_id).state My CeleryConfiguration is as following: app = Celery('<name>', broker='amqp://<user>:' + RABBITMQ_PASSWD + '@localhost:5672/<vhost>', backend='django-db', task_ignore_result=False, task_track_started=True, ) The backend is set and it works exactly every second time. I tried restarting the services, the computer and cleaning the databases. Same problem with different backends. Does anyone have an idea what could cause the problem? Thank you for your help! -
What to use instead of DO_NOTHING to only delete one field?
I want to link two models like this class t_data(models.Model): receiver = models.TextField() file_desc = models.TextField() file = models.FileField(upload_to='files') another model : class transaction_detail(models.Model): transaction_id = models.ForeignKey( t_data, on_delete=models.DO_NOTHING, ) sender=models.TextField() receiver = models.TextField() *yes i am using DO_NOTHING and i have read that it is wrong to use it. But it is not working. now when a user tries to delete his file, The t_data object should be deleted but the transaction_details should not change.There is nothing specific on my view for deleting objects. Yet, simple example would be def delete_request(request,id): requested = t_data.objects.get(id=id) requested.delete() return HttpResponseRedirect('/requests') When I try to delete the t_data object it throws an Integrity Error. How to solve it? Or what to use in place of DO_NOTHING? We can also use OneToOneField if you want to solve this problem. Thank you :) -
Is there a way to apply condition on django boolean field?
I am working on an multi-vendor Django base E-commerce project. I want radio button base selection like when a user add an item to cart I want him/her to choose (yes or no) Is this gift? when a user click on yes, I need to show a message input field where he/she can put custom message to print on item. There are multiple items in cart. Can Anyone guide me how to do this in django? Thank you in advance. -
Django : Run task in background immediately
Similarly to this question, I don't understand how the django-background-tasks module works. What I want is to have a button which would start a task in background so it doesn't block the front. The task has to be run as soon as the click occurs. Reading the docs I thought that I only had to define my task as a function preceded by the decorator @background(schedule=1) then calling the function would start the task one second after the click handler was run. Calling notify_user as normal will schedule the original function to be run 60 seconds from now: However this is not what happens. What happens is that a new task is created after each click (I could understand that by requesting the background_task database thanks to this answer) but none ever runs. The command python manage.py process_tasks seems to run one task defined previously before stopping. If no task has been defined, then it waits for a task to be defined for up to duration seconds (specified when running the command). This behavior is not what I expected while reading the documentation. duration - Run task for this many seconds (0 or less to run forever) - default is … -
How to check if the current user has already liked the post in the list view?
Im showing a list view of posts, posts can be liked and I would like to check whether the post is already liked by the user or not so I can show a like or unlike button. How do I do that? I guess it is somehow connected with related_name but do not know how exactly. Or can I put in the model or in the view and how to do this in the best way? user model - UserProfile is generated for each user class User(AbstractUser): pass class UserProfile(models.Model): user = ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.user.username def post_user_created_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post model class Post(models.Model): author = models.ForeignKey(UserProfile, on_delete=models.CASCADE) text = models.TextField() slug = models.SlugField(max_length=255, unique=True) timestamp = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(UserProfile, related_name="posts") the view class PostListView(generic.ListView): model = Post template_name = "posts/post_list.html" context_object_name = "posts" form = PostForm() def get_queryset(self): return Post.objects.order_by("-timestamp") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form return context def post(self, request, *args, **kwargs): form = PostForm(request.POST) if form.is_valid(): form.instance.author = get_author_userprofile(self.request.user) form.save() return redirect('posts:post-list') -
ftplib.error_temp: 451 Need to secure data channel first
I am trying to access an FTP client using django but I am getting this error: ftplib.error_temp: 451 Need to secure data channel first can anyone help me? i am using this part of the management command to upload the file Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/proteinforpets/applications/catalogue/management/commands/send_nielson_data.py", line 26, in handle self.upload_report_to_nielson(transaction_report) File "/home/ubuntu/proteinforpets/applications/catalogue/management/commands/send_nielson_data.py", line 102, in upload_report_to_nielson ftps.storbinary('STOR ' + os.path.basename(report_file), f) File "/usr/lib/python2.7/ftplib.py", line 772, in storbinary conn = self.transfercmd(cmd, rest) File "/usr/lib/python2.7/ftplib.py", line 378, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/usr/lib/python2.7/ftplib.py", line 722, in ntransfercmd conn, size = FTP.ntransfercmd(self, cmd, rest) File "/usr/lib/python2.7/ftplib.py", line 336, in ntransfercmd host, port = self.makepasv() File "/usr/lib/python2.7/ftplib.py", line 314, in makepasv host, port = parse227(self.sendcmd('PASV')) File "/usr/lib/python2.7/ftplib.py", line 251, in sendcmd return self.getresp() File "/usr/lib/python2.7/ftplib.py", line 224, in getresp raise error_temp, resp ftplib.error_temp: 451 Need to secure data channel first management command upload part def upload_report_to_nielson(*files): try: ftps = ftplib.FTP_TLS('namft.nielseniq.com') ftps.ssl_version = ssl.PROTOCOL_TLSv1_2 ftps.set_pasv(True) ftps.auth() ftps.prot_p() ftps.connect(port=21, timeout=80) ftps.login(settings.NIELSON_FTP_USER_NAME, settings.NIELSON_FTP_USER_PWD) except … -
How to define extra fields when creating super user in Django?
I have this in my models.py: class UserManager(BaseUserManager): def create_user(self, name, password=None): """ Creates and saves a User with the given name and password. """ if not name: raise ValueError('A user must have a name.') user = self.model() user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, name, password): """ Creates and saves a staff user with the given name and password. """ user = self.create_user( name, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, name, password, id): """ Creates and saves a superuser with the given name and password. """ user = self.create_user( name, id, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user The reason I added the field id in my create_superuser -method is that it is a required field in my model and I thought I need to include it also when running python manage.py createsuperuser. My problem is that I don't know how to customize the super user creation. With this I always get the error TypeError: create_superuser() missing 1 required positional argument: 'id'. I also tried to remove the id from the function. The process goes through without errors then, but I can't log in to the admin site, it says the username … -
How to hide and show "ADD" button in Django while using DRF
I'm Using Django framework as a backend, PostgresSQL for DB and HTML, CSS, Javascript for frontend. I want to show and hide "CHOOSE/ADD" button on table. If user added items in a table, then I want to hide the "CHOOSE/ADD" button and if user remove those items from table I want to show the "CHOOSE/ADD" button. Since I'm using Django Rest Framework to append the table with Help of Javascript. The Codes Goes here: Script to append table using DRF <script> $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showdata/', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td>'+data[i].product.title+'</td><td><a href="" class="btn btn-outline-danger"><i class="fas fa-trash"></i></a></td></tr>'); $("#history").append(row); } } }); }); </script> HTML TABLE: <tr > <th>History Books</th> <td id = "history"></td> <td><a href="{% url 'mainapp: history_book' %}"><button id="btnaddHistoryBook" type="button" class="btn btn-dark"><i class="fas fa-plus"></i>&nbsp;&nbsp;Choose Books</button></a></td> </tr>