Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a folder to Django?
So my question looks like this Creating a new project django-admin startproject firstapp Creating a new app python manage.py startapp blog So, my question is . I've added a new folder called "projects" within the app "blog" Django doesn't see the folder. How to connect? via INSTALLED_APPS (I've tried it doesn't work) -
social-auth-app-django error creating table for column social_auth_usersocialauth.created does not exist
I am not sure where is the issue and not sure why the auth package is not creating the table. but also the facebook individual verification is also disabled due to COVID-19. I don't get the option to verify which maybe why but I am not sure. [the table error I get when I try to login through Facebook oauth2][1] """ #settings.py file settings # pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) AUTHENTICATION_BACKENDS = ['social_core.backends.facebook.FacebookOAuth2','django.contrib.auth.backends.ModelBackend',] SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_KEY = '855857298498541' SOCIAL_AUTH_FACEBOOK_SECRET = '9f5f0e8af7834122773d5b5f4ec03cb4' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email, picture.type(large), link' } SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [ ('name', 'name'), ('email', 'email'), ('picture', 'picture'), ('link', 'profile_url'), ] SOCIAL_AUTH_REDIRECT_IS_HTTPS = True # SOCIAL_AUTH_POSTGRES_JSONFIELD = True # installed apps including all the packages INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django_extensions', 'storages', 'socialApp.apps.SocialappConfig', ] # middleware for the application MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] """ [1]: https://i.stack.imgur.com/j5Tnj.png -
Django: access __init__.py of project from within an app
This is the files structure: project -> my_project -> __init__.py -> my_app -> templatetags -> extras.py project/my_project/__init__.py contains: __version__ = '1.0.0' VERSION = __version__ # synonym I want to access VERSION or __version__ in project/my_project/my_app/templatetags/extras.py But if I try to: from my_project import VERSION I get ImportError: cannot import name 'VERSION' from 'my_project' What is the correct way to get the version string? Background: In extras.py I define a simple_tag with the version number so I can display the version number in templates. In this answer the version string is achieved by parsing the python file with a regex but this does not seem like an acceptable solution to me, and I'm sure there is a way to untangle this import knot. -
Django + React -> fetch / axios
I want fetch data to Django backend from React and request the params in url with 'request.GET.get("",None)' [or alternatives?]. The best case would be a solution for multiple params or in body. Every tutorial only shows fetch to models, but all references I found for request or create() the parameters in my views.py ( to do other stuff with values in views) did not work. //Form.js var url = 'http://127.0.0.1:8000/api/'+'?name='+name+'/' axios.post(url, { title: title, value1: value1, value2: value2, }) I want to scrap the 'name' from url (in next steps I need 'params' from body, too) in my views.py to do further action with the values. #views.py def my_view(request, name): request_name = request.GET.get("name", None) I think possible problem with the urls referenced param 'name', from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('admin/', admin.site.urls), path('api/', views.my_view ), path('api/<name>/', views.my_view ), #path('api/(?P<name>\d+)/', views.my_view), #re_path('api/<name>)/', views.my_view , name='name'), #re_path('api/(?P<name>\d+)/', views.my_view , name='name'), #path('api/<name>/)', views.my_view , name='name'), #re_path(r'^api/<name>/$', views.my_view), because, when I tried: fetch url 'http://127.0.0.1:8000/api/'+name+'/' -> without the '?name=' with this urls.py path('api/<name>/', views.my_view ) I can print(name) in views.py -> results is correct name def my_view(request, name): #request_name = request.GET.get("name", None) print(name) print(name) does … -
What "rc" stands for in the latest Python 3.91rc1 version name
as mentioned in the title.. What "rc" stands for in the latest Python 3.91rc1 version name? Thanks -
date and time is not showing its showing none instead
i am trying to show date and time in template but its shwoing none Here is models.py:: date = models.DateTimeField(blank=True, null=True, auto_now_add=True) Here is my templete: <td>{{order.date}}</td> -
Run a function from an imported module using Django
I'm trying to run a function from an imported class when the user clicks a button on the webpage. views.py def smartsheet_int(request): #if request.method == 'GET': from .platsheet.land_schedules import Schedule # call function sch = Schedule() sch.import_plats() return redirect('community-home') urls.py path('communities/actionUrl', smartsheet_int, name='actionUrl'), html <form action='actionUrl' method='GET'> <button type='submit' >Update Smartsheet</button> </form> When I click the button, it initializes the class and runs the function as expected. However, it doesn't work when I try to re-run it after changing data on the website. It doesn't generate an error...it's like it doesn't re-initialize the class or something (which needs to happen because the function is querying from Django's database). It will only work again if I stop the python server and re-start it again. Thoughts? -
Displaying a Decimal Field as a Slider in Django
I have defined a Decimal Field in my Forms.py class Slider(forms.Form): slider_form= forms.DecimalField(min_value=0.0, max_value=1.0, initial = 0.5, required=True, label=False, decimal_places=1, widget=forms.NumberInput(attrs={'step': "0.1"})) Is there a good way to convert the display to a slider in Django? Would it be better to attack this on the front-end instead using Javascript? -
drf-spectacular Can't find inspector class
I am trying to set up drf-spectacular to generate an AutoSchema for my djangorestframework API. I have set it up as explained in the Readme, e.g., in installed apps, version = "~=0.11.1", and in the rest framework settings as below: REST_FRAMEWORK = { ..., 'DEFAULT_SCHEMA_CLASS': ('drf_spectacular.openapi.AutoSchema',), } My djangorestframework is version 3.12. I am getting an error when I run the following command: ./manage.py spectacular --file schema.yml Here's an example view of mine: class LinkListView(ListView): permission_classes = [AllowAny] template_name = "core/linklist.html" context_object_name = "link_list" def get_queryset(self): return Org.objects.all() After reading a bunch on schemas, I'm thinking that I have some other library that is conflicting with this or that some previous other swagger alternatives are conflicting. Does this make sense based on the error? Is there something I'm missing to try? Thanks! Traceback (most recent call last): File "./manage.py", line 23, in <module> main() File "./manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle schema = generator.get_schema(request=None, public=True) File "/usr/local/lib/python3.8/site-packages/drf_spectacular/generators.py", line 188, in get_schema paths=self.parse(request, … -
How to implement a Refresh Token View in Django
I am using Django Rest Framework and the simple jwtToken. I have implemented the JWT authentication for the login and I get as a return an access and a refresh token. This works fine. However I don't know how to use the refresh Token. If we hit a specific endpoint, eg api/refresh with body params the tokens {access= '' refresh=''} I need to decode the access token to see if it has expired, then to get the users credentials hidden there (by default in the jwt the id) and then to give as a responce the new access token. How can I implement this? -
How to render raw HTML block from Rich Text Editor after Axios request?
So my backend is Django with Django Rest API and there I create my blog posts which are rendered in Nuxt page using "v-html" directive. Problem 1: Uploaded images inside of Rich editor in Django is not rendering in Nuxt (Aim is to be able to add pictures in the middle of blog post) Problem 2: Codeblocks (html code block with markdown) inserted in Rich Editor is being rendered in Nuxt without any styles, whereas the same codeblock being inserted as a Nuxt data object is rendered with styles. (Aim is to be able to insert codeblocks in rich editor so its rendered in Nuxt with styles) As a rich text editor in Django Admin I use Django-Trumbowyg. I searched everywhere, however couldn't find the proper solution! All the solutions I digged out in internet are "workarounds" and from my point of view its not the way it is supposed to be. I would more than glad if you could provide a reference if it's a duplicate or help me to find out a solid solution. :) -
User account gets Permission Denied Error but admin doesn't when uploading a file Django Apache
I deployed a Django app that allows users to upload files on a VPN running Debian and the app works for the admin i.e. I can upload files but whenever I try to upload a file as an ordinary user I get [Errno 13] Permission denied: '/file' The directory where all of the files are saved is called file. My user is called webcodefy. The current structure of the server is fms -> fms (virtual env) -> Django App, static folder, file folder. This is my default.conf file: # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html Alias /static /home/webcodefy/fms/fms/static <Directory home/webcodefy/fms/fms/static> Require all granted </Directory> <Directory home/webcodefy/fms/fms/WebApp> <Files wsgi.py> Require all granted </Files> </Directory> Alias … -
How to control the size of the image a user upload
I built my first django app as a website where artists can expose their paintings. I did it as part of my final project for CS50 so i'm not a professional and my knowledge knows many boundary !!! Now i tested it with a few user and found out that many uploaded very large photos (up to 55mb) and when i render the main gallery, the display image for all the paintings is the image1 so now my gallery has about 100 paintings and each time someone browse it upload all those massives photos to use as thumbnail on the gallery and it drain my bandwidth (i don't want this to cost me 200$/month) My question : is there a way to control the size of the image people upload ??? a kind of if photosize > 10mb: resize to 10mb else do nothing ... PS - The photos are uploaded to a S3 bucket Thanks -
How to make parent/child relationship work nicely in Django admin?
I'm using Django 3.1... I have a model setup like: class Order(models.Model): supplier = models.CharField("supplier",...) ... class OrderLine(models.Model): quantity = ... product = ForeignKey(Product, related_name='product', ...) order = ForeignKey(Order, ...) My admin looks something like class OrderLineAdmin(TabularInline) list_display = ('product', 'quantity',...) class OrderAdmin(admin.ModelAdmin): list_display = ... inlines = [OrderLineAdmin] I have three problems with the result. I would like to only show products in the inline product choices which are from the parent order supplier. Ideally, I would allow first selecting the supplier in the parent order and then have the inlines generated from that. It is very slow as it seems to be repeating the same query for every choice field to get all the products, I would like to cache that across all order lines. It seems like a pretty standard problem and I'm sure there's a good approach to it just couldn't work it out from the docs or other posts. Appreciate any pointers... -
how to apply the style in html for folium map in a Django template
I am not professional in Django and html. I want to build a very simple website in Django to just show a map from folium: here is my code: views.py: def home_map(request): # define the Map m = folium.Map(width=800, height=500, location=Point0, zoom_start=6) # loading database .... .... # Location marker num_of_data = len(Imported_database.index) for i in range(0, num_of_data): popup_t = (......) popup = folium.Popup(popup_t, min_width=100, max_width=500) folium.Marker([lat_p, long_p], tooltip='Some Data appears by click', popup=popup, icon=folium.Icon(color='purple')).add_to(m) # Converting exporting data to html format m = m._repr_html_() # convert the map to html view, in the html file: {{map|safe}} Imported_database = Imported_database.to_html() context = {'map': m, 'data': Imported_database} return render(request, 'home.html', contex) home.html: <body> <h1>Folium</h1> <div> <center> {{ map| safe }} </center> </div> </body> It shows the map very well. But I want to bring the map to the center of the html page. ( I want to do other styles also) I tried many tags in html but didn't work! -
Django Annotation + Distinct field
I have three models defined like this: class Match(models.Model): id = models.IntegerField() class Market(models.Model): match = models.ForeignKey(Match,on_delete=models.CASCADE) class Issue(models.Model): market = models.ForeignKey(Market,related_name='issues',on_delete=models.CASCADE) volume = models.PositiveIntegerField() It is structured like this: Every Match has several Market, and every Market has several Issue. What I want to do is: For each Match, select the Market that has the largest sum of Issue.volume It may sound quite easy, but I can't figure it out... What I've done so far: Without the DISTINCT Match condition Market.objects.annotate(total_volume=Sum('issues__volume')).order_by("-total_volume") This works as expected, but a single Match occurs multiple time in my QuerySet. First try with the DISTINCT Match condition Then I'm trying to add a DISTINCT(Match). As I'm using Postgresql, I can use distinct('match_id'): Market.objects.annotate(total_volume=Sum('issues__volume')).order_by("match","-total_volume").distinct("match_id") But it raises the following error: NotImplementedError: annotate() + distinct(fields) is not implemented. Second try with the DISTINCT Match condition I achieved to get what I expected using: Market.objects.values('match_id').annotate(total_volume=Sum('issues__volume')).order_by("-total_volume") However, I want to access to every Issue linked to a specific Market, which is impossible here because of the use of values(). Do you have any ideas on how to make it work with as few requests as possible? Thank you for your help! -
what is the correct way of defining django-extensions
I need to use Django-organizations and it seems I need to install Django-extensions. I included both to the list of installed apps but when I tried to run the dev server I get the following traceback message: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\organizations\fields.py", line 81, in <module> BaseSlugField = getattr(import_module(module), klass) File "C:\Users\stephen\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 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-extensions' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", … -
Filter django view with or condition
If I want to limit an object in Django within my view to show a filtered list based on if a user is added or if the user is an author, how can I create that condition? I attempted to filter with an or statement but this just displayed duplicates. return Group.objects.filter(author=user or users__in=[user]) What would be the proper way to format or create this logic? -
can't set max height with respect to screen heigth of a div with bootstrap
i'm using bootstrap with Django and i've been trying to set the max height of a div = 75% of the screen height because it has a large picture in it. so i'm trying to resize the parent div of the image to 75% of the device screen but this doesn't seem to work. i've used class="mh-75" and it doesn't work. i went further to load static css file to style this with max-height: 75%; and it still doesn't work. here's the code: {% extends 'testapp/base.html' %} {% block content %} {% for image in Image %} <div class= "container-fluid pd-2 pt-2 mh-75"> <div class="bg-dark text-white rounded p-1"> <img class="img-responsive img-wid img-fluid mx-auto d-block" src="{{ image.url }}" alt="{{ image.name }}"> <div class="pt-2 text-center"><p>Source: {{ image.source }}</p></div> </div> </div> {% endfor %} {% endblock content %} i don't think this would help but img-wid style: .img-wid{ max-width: 99.999%; } -
problem: facing problem running this code
showing 'keyword error' 'search' This is a python project that takes the item you want to search on Flipkart as input generates and prints the URL of that product This file has the headings- Product_Name, Pricing, Ratings and Link with the entities of Flipkart's first page below it. when run this code the interpreter shows the missing keyword argument `BASE_FLIPKART_URL = 'https://www.flipkart.com/search?q={search}'` # Create your views here. `def home(request):` ` return render(request, 'base.html')` `def new_search(request):`**strong text** search = request.POST.get('search') Search.objects.create(search=search) final_url = BASE_FLIPKART_URL.format(quote_plus(search)) page = request.get(final_url) soup= bs(page.text,"html.parser") product =[] amount =[] point =[] allData = soup.find_all("div",{'class' : "_2kHMtA"}) ``` final = [] for post in allData: name = post.find('div', {'class': "_4rR01T"}) product = name.text # print(product) price = post.find('div', {'class': "_25b18c"}) amount = price.find('div', {'class': "_30jeq3 _1_WHN1"}).text # print(amount) rate = post.find('div', {'class': "_3LWZlK"}) point =rate.text # print(point) final.append((product,amount,point)) stuff_for_frontend = { 'search': search, 'final' : final, } return render(request,'search/new_search.html',stuff_for_frontend) -
Create a csv file after the first time user logs in
Is there any way of checking when a user logs in for the first time and then create a file? Pseudocode: if first_time_login == True: create_some_file -
Django: Unable to set background-image to a button in template
I am trying to set a background-image to a button but its not displayed. In the inpect element when I hover over the background url it displays the image. Meaning the url is correct. <button style="background-image: url('{{ mobile_brand.image.url }}'); !important; background-repeat: no-repeat;" name="brand" id="brand" class="btn btn-outline-info m-1" type="submit" value={{mobile_brand}}></button> I have tried different variations like using input instead of button. Putting static in the url. Removing comas, background-repeat. And tried giving the full path. Nothing works. Thankyou for any help. -
How can I display 2 models In 1 view?
So I have a Django app where I want the user to be able to input a question and then like 3 choices for another user to guess Models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Question(models.Model): question = models.CharField(max_length=255) body = models.CharField(max_length=200) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.question def check_answer(self, choice): return self.choice_set.filter(id=choice.id, is_answer=True).exists() def get_answers(self): return self.choice_set.filter(is_answer=True) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Choice(models.Model): question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) is_answer = models.BooleanField(default=False) def __str__(self): return self.choice_text def get_absolute_url(self): return reverse('article_list') and then my views.py from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin ) from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Question from .forms import QuestionAddForm, EditQuestionForm, ChoiceAddForm class QuestionListView(LoginRequiredMixin, ListView): model = Question template_name = 'article_list.html' class QuestionDetailView(LoginRequiredMixin, DetailView): model = Question template_name = 'article_detail.html' class QuestionUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Question fields = ('question', 'body') template_name = 'article_edit.html' def test_func(self): obj = self.get_object() return obj.author == self.request.user class QuestionDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Question template_name = 'article_delete.html' success_url = reverse_lazy('article_list') def test_func(self): obj = self.get_object() return obj.author == self.request.user class QuestionCreateView(LoginRequiredMixin, … -
Disqus comment section in Django blog not showing but only in 1 post
I can create new posts and Disqus comments will appear as well as in my old posts But for some reason not in this one. They all use the same code, It doesn't have sense to me. Didn't find any info on this issue. https://gsnchez.com/blog/article/El-var-como-medida-del-riesgo-de-mercado. This is the url, u can check it online. <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = gsnchez.com{{ request.get_full_path }}; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = {{post.id}}; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://gsnchez.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> -
Django query merge
I have two model classes on the "models.py" file. Signup & Notes from django.contrib.auth.models import User from django.db import models # Create your models here. class Signup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) contact = models.CharField(max_length=10, null=True) branch = models.CharField(max_length=30) campus = models.CharField(max_length=30) role = models.CharField(max_length=15) def __str__(self): return self.user.username class Notes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) uploadingdate = models.CharField(max_length=30) branch = models.CharField(max_length=30) subject = models.CharField(max_length=30) topic = models.CharField(max_length=200) notesfile = models.FileField(null=True) filetype = models.CharField(max_length=30) description = models.CharField(max_length=300, null=True) status = models.CharField(max_length=15) def __str__(self): return self.user.username + " " + self.status on my function i uses notes = Notes.objects.all() & users = User.objects.all() to get them. here is the funtion def indexnotes(request): notes = Notes.objects.all() users = User.objects.all() d = {'notes' : notes,'users' : users} return render(request,'indexnotes.html',d) I am using a for loop to show the values on a datatable. The code is like this <tbody > {% for i in notes %} <tr> <td>{{forloop.counter}}</td> <td>{{i.user.first_name}} {{i.user.last_name}}</td> <td>{{i.uploadingdate}}</td> <td>{{i.campus}}</td> <td>{{i.subject}}</td> <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td> <td>{{i.filetype}}</td> <td>{{i.description}}</td> <td>{{i.status}}</td> <td><a href="{% url 'assign_status' i.id %}" class="btn btn-success" >Assign&nbsp;Status</a></td> <td><a href="{% url 'delete_notes' i.id %}" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</a></td> </tr> {% endfor %} </tbody> Now the problem is some value of the table …