Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to combine AJAX + view function (API call) + url mapping the smart way?
I have a Javascript/AJAX function that assigns the team_id of a soccer team to a variable on 'click' of the teams name in the sidebar (see below for a screenshot). This variable shall then be used to make the according API call to get fresh data to update the dashboard as requested. The web application/dashboard is Django based. The Javascript itself assigns the variable smoothly and the views function itself fetches data from the API as well (when using a fix API URL without the assigned variable). To make this thread a future guidance for similar issues, i divided the content in different questions and tried to present it as neat as possibe. 1.) Now when I want to combine these steps i always end up with a TypeError (because the API call doesn't return any data) since the views function seems not to use the assigned variable 'team_id' within the API url (the team_id is emtpy when debugging = no API data in return). Why is that? 2.) I also tried to change the logic of the url mapping that way (which I would prefer) that there is only one url e.g. www.dasocc.com to display the dashboard and the … -
Using django url tag inside jquery ajax
I am building a page which holds some categories and when user clicks on a link, then I go ahead and fetch the details for that specific category (products of that category). The way to do this, I thought, was to use jQuery Ajax. Anyway, the part where i append my data is like this: ... $.ajax({ ... success: function(results) { $("#cards").empty(); for (let iterator = results.length -1; iterator>=0; iterator--) { $("#cards").append( '<a href="{% url "product" '+results[iterator].id+' %}">' +'<div>' + '<div class="card mb-5 shadow-sm">' + '<img class="card-img-top"' + 'src="'+results[iterator].image+'" />' + '<div class="card-body">' + '<h5 class="card-title">'+results[iterator].name+'</h5>' + '<p class="card-text">'+results[iterator].price+'</p>' + '</div>' + '</div>' +'</div>' +'</a>' ); } }, ... }); ... Based on this block of code, i get this error: Reverse for 'product' with arguments '('+results[iterator].id+',)' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$'] Since i get the results in form of json i don't have a problem with using it the way i did, but the problem rises when adding the a tag around my container div. I don't understand what course of action I should take since i'm not really experience with neither Django nor jQuery. -
Django + nginx + gunicorn not serving static files
Sorry for kind of repeating question, I know that similar questions has been asked before, but none of them helped to find solution. I am very new to whole web development thing and been struggling with this problem for couple of days now. My website do not show static files then I turn off debug mode. To my understanding that's why i should use nginx. I configured everything according to this guide. Following guide I put my static files into /opt/myenv/static/ directory. Done collectstatic command, created symbolic link (to my understanding), restarted nginx but still if I turn off debugging I see no static files served. My nginx config: server { server_name stvskaiciuokles.eu; access_log off; location /static { alias /opt/myenv/static/; } location /media { alias /opt/myenv/STV_skaiciuokle/skaiciuokle_web/media/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded_Host $server_name; proxy_set_header X-Real_IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } My settings.py relevant part: STATIC_URL = '/static/' STATIC_ROOT = '/opt/myenv/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Please help me determine what is wrong, since I cannot find any suitable solution despite reading multiple similar questions online? Guide I used is from 2013 maybe syntax changed a … -
django uwsgi - "No module named 'project'"
I'm trying to set up a Dockerised django/uwsgi stack. When I start the containers, uWSGI logs a "ModuleNotFoundError: No module named 'project'". I'm obviously doing something dumb, but I can't see what. Following the guide here, my dir tree looks like: mysite docker-compose.yml manage.py project __init__.py urls.py wsgi.py settings __init__.py base.py local.py The django docker container mounts the entire mysite dir as /mysite. My uwsgi INI file contains: chdir = /mysite/project module = project.wsgi:application env = DJANGO_SETTINGS_MODULE=project.settings.local (I've also tried with chdir = /mysite) What simple and obvious mistake am I making here? -
Foreign key issue in UserProfile django
I want to retrieve User profile data of User who is logged in. e.g. Based on logged in user I want to retrieve the country of the user from userprofile. Seems straightforward but I am missing some fine print. Tried a lot but no success. Need help. I tried and referred django document but I am a newbie I am having following model. class User(AbstractUser): username = models.CharField(max_length=100,blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) title = models.CharField(max_length=5) dob = models.DateField() address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) photo = models.ImageField(upload_to='uploads', blank=True) -
django - upload file to folder and show the current logged in username in the uploadform
I have a userprofile that captures the username and the group the user is assigned to. I want the uploaded files to be saved under the group name folder. The folders already exit at the media root, the files shoud be routed to these folder I solved the problem by the solution given. Now the username is shown as a dropdown list on the upload page. I want only the logged it username to be shown or exclude even showing it models.py class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, verbose_name='Username') tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") # validators=[FileExtensionValidator(allowed_extensions=['tar', 'zip'])] def __str__(self): return self.request.user.username class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username view.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') forms.py class uploadmetaform(forms.ModelForm): count = Metadataform.objects.all().latest('id').id #To know the id of latest object data = Metadataform.objects.all().filter(id=count) #return the queryset with only latest object path = forms.ModelChoiceField(queryset=data) def __init__(self, *args, **kwargs): super(uploadmetaform, self).__init__(*args, **kwargs) count = Metadataform.objects.all().latest('id').id data = Metadataform.objects.all().filter(id=count) self.fields['path'] = forms.ModelChoiceField(queryset=data) class Meta: model = uploadmeta … -
Making a Page in Django to render data from API?
I Have a problem statement where i have a RShiny Code and i have converted it into an API using Plumber . I want to create page in django which should take input from user and then hit that pi hosted and display the rendered JSON output from that api. Can anybody guide me what should i go forward to do this ? -
How to find area of Polygon intersection to annotate GeoDjango query?
In my model, I have a Polygon Field. In my query, I would like to compute the area of the intersection between this field, and a predetermined circle, in order to find the proportion of the circle's area that is recovered by my Polygon model field. Here is my model definition: class WDPA(models.Model): site_code = models.CharField(max_length=200, primary_key=True) site_name = models.CharField(max_length=300) iucn = models.IntegerField(default=0) geom = models.MultiPolygonField() Here is my query: tile = Tiles.objects.filter(start_long__gte=float(form.cleaned_data.get("latitude")), end_long__lte=float(form.cleaned_data.get("latitude")), start_lat__lte=float(form.cleaned_data.get("longitude")), end_lat__gte=float(form.cleaned_data.get("longitude")) )[0] tiles = [tile.tile_id, tile.near_0, tile.near_1, tile.near_2, tile.near_3, tile.near_4, tile.near_5, tile.near_6, tile.near_7] center = Point(float(form.cleaned_data.get("longitude")), float(form.cleaned_data.get("latitude")), srid=4326) circle = center.buffer(0.01802) zones = WDPA.objects.filter(tiles__in=tiles).annotate( distance=Distance('geom', center) ).order_by('distance').filter(distance__lte=2000).annotate( intersection=ExpressionWrapper(F('geom'), output_field=PolygonField()).intersection(circle).area ) But I can't call .intersection() method, it causes this error: AttributeError: 'ExpressionWrapper' object has no attribute 'intersection' I also tried to use an Intersection object, but I can't call the area either in my annotate. Does someomne as a solution please ? Thanks in advance -
Django-money. When display in template it's showing wrong format of currenncy
I have a problem with displaying currency by django-money module. In template I used 2 options: {{ object.balance }} and {% money_localize object.balance %}. I expected to see on website $100.00, but I got US$100.00. Any ideas, why it's display this way? My model class has field: balance = MoneyField(_('Balance'), max_digits=25, decimal_places=2, default=Money(0, "USD")) -
Django annotate first occurrence of x in sorted queryset
I have a queryset where the owner's objects are displayed first then objects not owned by them are followed. MyModel.objects.annotate( sort=Case( When(owner=self.request.user, then=0), default=1, output_field=IntegerField() ) ).order_by('sort', 'name') Now if that produced the following, how can I annotate the first occurrence that the owner is not the request user so that obj_list[2]['first_occurrence'] = True? obj_list = [ {'owner': 1, 'name': 'B', 'sort': 0}, {'owner': 1, 'name': 'D', 'sort': 0}, {'owner': 6, 'name': 'A', 'sort': 1}, ... ] Alternatively is there a way to get the first occurrence (without regrouping) where request.user != obj.owner so that I can insert an extra table row? {% for obj in obj_list %} {% if obj.first_occurrence %} ... {% endif %} ... {% endfor %} -
Unabe to make migrations to herokuapp: No module named 'django-heroku'
After finally deploying my app to heroku I wanted to make migrations to my postgres database. I ran into a curious error: (movie_app) ejan@linux-nr9m:~/github/Moviebase-web-app> heroku run python manage.p makemigrations Running python manage.py makemigrations on ⬢ rate-star-movies... up, run.2515 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 15, in check_all_models models = apps.get_models() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 178, in get_models self.check_models_ready() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias in self: File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in … -
Django Elasticsearch results highlighting problem
I'm making a site, almost finished and I have implemented the basic search into my site using Elasticsearch (5.6) and Haystack. I followed the tutorial, built the indexes connected everything and the search is working. Now I would like to highlight the search results with the query word. ( so if the word is Batman, I would like all instances of the word Batman to be highlighted on the page ). I read through elasticsearch documentation ( https://www.elastic.co/guide/en/elasticsearch/reference/6.4/search-request-highlighting.html ), and there I found examples like: GET /_search { "query" : { "match": { "content": "kimchy" } }, "highlight" : { "fields" : { "content" : {} } } } I'm still not sure how is this supposed to work, I have been searching since yesterday. I downloaded postman and tried getting this to work using that, but honestly I got no idea what I'm doing. Anyone kind enough to point me to some docs or help me out with that one, I really can't seem to work out how is that supposed to work :( Next, after failing with that, I tried this : https://django-haystack.readthedocs.io/en/v2.4.1/highlighting.html The problem here is that I get an <form class="search" method="get"> <i class="fa fa-search search-icon"></i> … -
Unable to run Python Django Oscar sandbox website on Windows
I wanted to learn how to use Django and Oscar to create an e-commerce website. I was initially trying to follow some tutorials but almost all of them use some old version. Finally, I tried to follow the official documentation. The only problem is that the instructions on the website seem to be for Linux. (https://django-oscar.readthedocs.io/en/2.0.2/internals/sandbox.html). Here are my commands I wrote in the terminal: git clone https://github.com/django-oscar/django-oscar.git cd django-oscar virtualenv oscar oscar\Scripts\Activate These commands seem to have created all the folders. However, make sandbox sandbox/manage.py runserver throws an error about the make not being recognized. I installed MinGW on my Windows but this did not seem to make any difference. If I try to run the manage.py runserver command directly. cd sandbox manage.py runserver I get the following error: ModuleNotFoundError: No module named 'django' How can I get the sample Django Oscar project to run? Thanks. -
Strange Bug : List.append in Python erasing precedent input and cloning the new one instead each
Ok I have been working many times with list in python and it s the first time I encounter this problem : Near the strange place I've got this ( simplified ) list = [] dict = {} things = {'1':'Am', '2':'I', '3':'Dumb?'} [...] for key,value in things.items(): if value: dict[key]=value print(dict) list.append(dict) print(list) And get the this result : {'1':'Am'} [{'1':'Am'}] {'2':'I'} [{'2':'I'},{'2':'I'}] {'3':'Dumb?'} [{'3':'Dumb?'},{'3':'Dumb?'},{'3':'Dumb?'}] hinhin, someone have ever get this ? I, m stuck, thank iou :) -
Saleor comes with react by default. Can we have a 'basic' Saleor without frontend frameworks?
I wanted to use Saleor for a "single-type-product" e-commerce website. I installed Saleor yesterday but it has a huge requirements file, including react.js and many other frontend stuff. I don't want them. Is it possible to install Saleor without anything else? Or at least, with the least other requirements? -
Creating own ordering class
I need to order all stories by popularity(rating field), lass added(created_at field) and by genres(genre field(Foreign key)). Now it only works for last added, how can I add two more order in my CustomOrdering class? class CustomOrdering(OrderingFilter): allowed_filters = ['top', 'new', 'genres'] def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [params.strip() for param in params.split(',')] ordering = [f for f in fields if f in self.allowed_filters] if ordering: return ordering return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: ordering = ['-created_at'] if ordering: return queryset.order_by(*ordering) return queryset class StoryView(viewsets.ModelViewSet): queryset = Story.objects.all() serializer_class = StorySerializer filter_backends = (CustomOrdering, ) -
django template issue with django admin
from .models import Info from django.forms import ModelForm class NewInfo(ModelForm): class Meta: model = Info #fields = ('first_name', 'last_name', 'address') exclude = () -
Django HTML form input to db.sqlite3
I'm making a simple web server to take html input data and insert it to data base table . I've tried with POST request got into more CSRF troubles , Turned to GET request to go over CSRF (not necessary in my case ) , still not able to make it . myapp/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=300, unique=True) content = models.TextField() myapp/templates/createpost.html <head> <title>Create a Post </title> </head> <body> <h1>Create a Post </h1> <form action="" method="GET"> {%csrf_token%} Title: <input type="text" name="title"/><br/> Content: <br/> <textarea cols="35" rows="8" name="content"> </textarea><br/> <input type="submit" value="Post"/> </form> </body> </html> myapp/views.py from django.shortcuts import render from .models import Post def createpost(request): if request.method == 'GET': if request.GET.get('title', None) and request.GET.get('content', None): post = Post() post.title = request.GET.get('title', None) post.content = request.GET.get('content', None) post.save() return render(request, 'createpost.html') else: return render(request, 'createpost.html') am using Django 2.2.6 with PyCharm community 2019.2.3 I've been searching for almost 2 days , checked django doc , and stackoverflow answers , none was helpful , I had to ask to make sure its not a version related issue and forgive me if i miss understand a simple point am just a beginner. -
How to validate username in django forms?
Here I am trying to validate username and email in my forms but validating username is not working. But validating email is working fine. How can I validate username here? forms.py class RegisterUserForm(UserCreationForm): def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('Sorry this email address already exists.') return email def check_username(self): username = self.cleaned_data['username'] if len(username) < 6: raise ValidationError('Username must be 6 characters long.') return username class Meta: model = User fields = ['username', 'password1', 'password2','email'] -
How to avoid integrity errors occuring because of concurrent creations/updates?
So let's say there's a model A which looks like this: class A(model): name = char(unique=True) When a user tries to create a new A, a view will check whether the name is already taken. Like that: name_taken = A.objects.get(name=name_passed_by_user) if name_taken: return "Name exists!" # Creating A here It used to work well, but as the system grew there started to appear concurrent attempts at creating A's with the same name. And sometimes multiple requests pass the "name exists check" in the same few milliseconds, resulting in integrity errors, since the name field has to be UNIQUE, and multiple requests to create a certain name pass the check. The current solution is a lot of "try: except IntegrityError:" wraps around creation parts, despite the prior check. Is there a way to avoid that? Because there are a lot of models with UNIQUE constraints like that, thus a lot of ugly "try: except IntegrityError:" wraps. Is it possible to lock as to not prevent from SELECTing, but lock as to prevent from SELECTing FOR UPDATE? Or maybe there's a more proper solution? I'm certain it's a common problem with usernames and other fields/columns like them, and there must be a … -
How to Log Out from Keycloak from Django Code
Can not log out from keycloak IDP from inside of Django app code. All stackoverflow answers did not work fo me (most are for older version of the components involved), the same goes for the keycloak documentation. Recently another programmer implemented keycloak-based athentication for our Django-based website. Works fine for auth. The app is build by docker, three containers: the website on port 8000, keycloak db (postgres image), keycloak (jboss/keycloak image) on port 8080. Now I have to add "Logout" functionality to it, meaning singing out of keycloak from my Django code, and redirect the user back to the keycloak login screen. Django 2.2 Python 3.5 keycloak 7 social-auth-app-django 3.1.0 social-auth-core 3.2.0 settings.py SOCIAL_AUTH_KEYCLOAK_KEY = '<some keycloak key>' SOCIAL_AUTH_KEYCLOAK_SECRET = 'some keycloak secret' SOCIAL_AUTH_KEYCLOAK_PUBLIC_KEY = 'some public key' SOCIAL_AUTH_KEYCLOAK_AUTHORIZATION_URL = 'http://<some ip>:8080/auth/realms/<some realm>/protocol/openid-connect/auth' SOCIAL_AUTH_KEYCLOAK_ACCESS_TOKEN_URL = 'http://<some ip>:8080/auth/realms/<some realm>/protocol/openid-connect/token' SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' SOCIAL_AUTH_KEYCLOAK_ID_KEY = 'email' SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_URL_NAMESPACE = 'social' LOGIN_REDIRECT_URL = 'http://<website ip>:8000/' LOGOUT_REDIRECT_URL = 'http://<website ip>:8000/' SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.debug.debug', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.debug.debug', ) docker-compose.yml version: '3' services: web: restart: unless-stopped container_name: web-container build: context: . dockerfile: Dockerfile.dev ports: - "8000:8000" environment: PRODUCTION: 'false' … -
Django Admin Area "TextField" replacement. Issue with greek characters
I have replaced the standard Django "TextField" field with TinyMCE, CKEditor and Froala. When I type a greek word inside the editors (all of them) in the Admin Area, the result in the frontend app is HTML codes. For example, I type my name Αδριανός and I see <p>&Alpha;&delta;&rho;&iota;&alpha;&nu;ό&sigmaf;</p> I use Postgres with encoding=UTF8, Collate=English_United States.1253, CType=English_United States.1253 -
django opened file type to python opened file type
I have a django app that asks the user to upload an image. I get the image from html django. This image I pass to the python script as a parameter. I did a lot of stuff with this image (like using the PIL libraries), the class of the parameter is: 'django.core.files.uploadedfile.InMemoryUploadedFile' But the problem comes when I try to use one function that ask for the predeterminate type of .open() of python, that is: '_io.BufferedReader' Concretely, the function I'm using is: block_blob_service.create_blob_from_stream() (a Microsoft Azure function) So my question is, can I convert from django opened file type to python opened file type? It may be without saving the file and opening again. And, if by any chance, somebody has worked with this library, I've also tried block_blob_service.create_blob_from_bytes() and it's not working (to convert from django to bytes I've just done img = django_input.read() (I get a Bytes type) and block_blob_service.create_blob_from_path(), is not an option, because I can't get the path of the file, nor I don't want to save the image and get a new path. -
How to pass blank=false behavior to model form validation in django?
I have this model: Class MyModel(Model): other_field = CharField(max_length=200, null=True) my_field = BooleanField(null=True) and have this modelform class MyModelForm(ModelForm) class Meta: model = MyModel fields = ('my_field', ) my view: def my_view(request): template_name = 'my_template.html' context = {} if request.POST: my_model_form = MyModelForm(request.POST) if my_model_form.is_valid(): my_model_form.save() return redirect('other_url') else: my_model_form = MyModelForm() return render(request, template_name, context) in template I have: <form method="post" novalidate> <div> {% csrf_token %} {% form.as_p %} </div> <button>Save changes</button> </form> What I expect is that because in my_field I do not have blank=True`` and as a result it isblank=False, and I havenovalidate, I should not be able to save the form. But I see no validation error even if I leave my_field blank. However,other_field``` can not be left blank. -
how to use collapse in dynamic content when retrieving from database?
i have a bootstrap card that contains data retrieved from the database where this card has a card header that includes a link that is used to collapse extra data (hide/show) inside each card. what in my opinion is a logic is to get the id of each card and make the link open the selected card and not as a static card. the problem is that when i click the link nothing happen and there is now error. urls.py path("displaydata/<int:id>/",displaydata,name = "displaydata") views.py def displaydata(request,id): c = cursor.execute('SELECT ID,Nickname_,Date_of_Birth FROM Person_ WHERE ID = id ') print("c ===>",c) while True: result = c.fetchone() if result == Nonedjan: break print("result ===>", result) return redirect("search") return render(request,"displaydata.html",{"c":c}) pictureCard.html <div class="container"> <div class="row justify-content-center"> {% for obj in object_list %} <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-5"> <div class="p-2 my-flex-item"> <div class="card innercardzoom"> <div class="inner"> <img src="{% static '/img/card/1.png'%}" class="card-img-top" alt="..."> </div> <h5 class="card-header"> <a class="collapsed d-block" data-toggle="collapse" href="{% url 'displaydata' obj.0 %}" aria-expanded="true" data-target = "#table-collapsed" caller-id ="" aria-controls="collapse-collapsed" id="heading-collapsed"> <i class="fa fa-chevron-down pull-right"></i> details <script type="text/javascript"> $(document).on('click','.collapsed d-block',function(){ $('#heading-collapsed').attr('caller-id',$(this).attr('id')); }); </script> </a> displaydata.html {% for row in c %} <div id="table-collapsed" class="collapse" aria-labelledby="heading-collapsed"> <table class="card-body table-sm table table-hover text-right"> <tbody> …