Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wagtail pagination, django, wagtail, python
I would be very grateful if someone can help me out on this. I am developing a wagtail site but am short on configuring pagination which when clicking through (ie it just returns the page but not the results), so I have pagination working but when I click, it just returns the page number but does not return the actual model. My code is this: from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator class BlogIndexPage(RoutablePageMixin, Page): introduction = models.TextField( help_text='Text to describe the page', blank=True) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Landscape mode only; horizontal width between 1000px and 3000px.' ) content_panels = Page.content_panels + [ FieldPanel('introduction', classname="full"), ImageChooserPanel('image'), ] def children(self): return self.get_children().specific().live() def get_context(self, request, *args, **kwargs): context = super(BlogIndexPage, self).get_context(request, *args, **kwargs) all_posts = BlogPage.objects.descendant_of( self).live().order_by( '-date_published') paginator = Paginator(all_posts, 9) page = request.GET.get("page") try: posts = paginator.page(1) except PageNotAnInteger: paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context["posts"] = posts return context in my html I have the following: {% extends "base.html" %} {% load wagtailcore_tags navigation_tags wagtailimages_tags %} {% block content %} {% include "base/include/header-index.html" %} <div class="col-12"> {% if tag %} <p>Viewing all blog posts by <span class="outline">{{ tag }}</span></p> {% endif %} {% if page.get_child_tags … -
How to override handler404 and handler505 error in django?
How do i override the handler404 and handler505 error in django? i already change the DEBUG TRUE into False in my settings.py. this is my views.py def Errorhandler404(request): return render(request, 'customAdmin/my_custom_page_not_found_view.html', status=404) def Errorhandler500(request): return render(request, 'customAdmin/my_custom_error_view.html', status=500) this is my urls.py handler404 = customAdmin.views.Errorhandler404 handler500 = customAdmin.views.Errorhandler500 urlpatterns = [ ..... ] this is the error this is the documentation i follow https://micropyramid.com/blog/handling-custom-error-pages-in-django/ -
AWS CI CD with codepipline error - attached log
I'm trying to deploy a Django project with code pipleine what I've done : Created Elastic beanstalk env py version 3.6 eb-activity.log returns this error I tried running pip upgrade on the env pushing to git but that didn't fix it. Any suggestions ? :) [2020-09-21T08:53:56.134Z] INFO [19227] - [Application update code-pipeline-1600678386608-0fd34dae5393dbc6a31d126a16f4daabf6dc966d@6/AppDeployStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting appdirs==1.4.4 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/3b/00/2344469e2084fb287c2e0b57b72910309874c3245463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl Collecting apturl==0.5.2 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) (from versions: ) No matching distribution found for apturl==0.5.2 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) You are using pip version 9.0.1, however version 20.2.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2020-09-21 08:53:56,127 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (ElasticBeanstalk::ExternalInvocationError) caused by: Collecting appdirs==1.4.4 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Using … -
Django REST Framework page_size per view is not working as expected
I'm using Django 2.2 and Django REST Framework The DRF settings are REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'tools.rest_framework.pagination.StandardResultsPagination', 'PAGE_SIZE': 10, } Where the pagination class is customised to remove the URL for next and previous page and use page number instead. class StandardResultsPagination(PageNumberPagination): def get_next_link(self): if not self.page.has_next(): return None return self.page.next_page_number() def get_previous_link(self): if not self.page.has_previous(): return None return self.page.previous_page_number() I have two views where I want to customise the number of records per page class DataCreateListView(generics.ListCreateAPIView): serializer_class = DataSerializer pagination.PageNumberPagination.page_size = 20 class DataMinimalListView(generics.ListAPIView): serializer_class = DataMinimalSerializer pagination.PageNumberPagination.page_size = 5 and URLs defined are urlpatterns = [ path('data/minimal/', views.DataMinimalListView.as_view()), path('data/', views.DataCreateListView.as_view()) ] But when I visit the path https://example.com/data/ It gives only 5 records instead of 20. But when I remove the page_size from the DataMinimalListView then it gives 20. -
How to autoformat django html template tags in vscode
I've started learning Django and I'm using vs-code. I'm facing problem in auto-indentation of Django template html tags. I've tried so many formatters and extensions, searched everywhere, but cannot find a prettier like formatter which can indent the Django-html file template tags. <div class="col"> {% if something.someval >= 0 %} <p class="card-text">Value: {{ object.value }}</p> {% else %} <p class="card-text">Value: {{ object.other_val }}</p> {% endif %} </div> I want this to be indented as: <div class="col"> {% if something.someval >= 0 %} <p class="card-text">Value: {{ object.value }}</p> {% else %} <p class="card-text">Value: {{ object.other_val }}</p> {% endif %} </div> Can anyone please point me to appropriate extension or option? Thanks! -
How to acces instance variables in python within the class?
I am trying to write a form in Django in which a ModelChoiceField filters its options in a query using some input arguments from the constructor. I somehow do not quite understand how instance variables are supposed to work in Python... How can I acces the value of self.prev_status_no outside of init? I get an unresolved refernce error. class ShoppingCartStatusChangeForm(forms.Form): def __init__(self, *args, **kwargs): self.prev_status_begin = kwargs.pop('prev_status_begin') self.prev_status_no = kwargs.pop('prev_status_no') super(ShoppingCartStatusChangeForm, self).__init__(*args, **kwargs) status = forms.ModelChoiceField( queryset=StatusDefinition.objects.all().filter( shc_or_po="ShC").filter( step_number=(self.prev_status_no + 1))) status_begin_date = forms.DateTimeField() comment = forms.CharField() -
Display maps with Django and manipulate data?
i didn't find any recourses about how can I display maps with my Django projects and work on them -
How to fix standard_init_linux.go:211: exec user process caused "no such file or directory" error?
I try to "dockerize" a Django app. I work on Windows 1O and my project will deployed on Linux server. I build/run my containers. But my web app is in a loop "Restarting (1). x second ago" I do docker logs id_web_container I got an error standard_init_linux.go:211: exec user process caused "no such file or directory" so error might come from my entrypoint.sh file because of path... but when looking my Dockerfile file, I first set a work directory, copy the entrypoint.sh in this directory and then execute the file... what is wrong? # Pull the official base image FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev # Install dependencies COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt # Copy the entrypoint.sh file COPY ./entrypoint.sh . # Copy the project's files COPY . . # Run entrypoint.sh ENTRYPOINT [ "/usr/src/app/entrypoint.sh" ] -
How to Link Models in Django? ForiegnKey vs Parent Linking
I want to link stdClass and stdDetails with schoolDetails in such a way that I can access stdClass and stdDetails via schoolDetails without rendering the whole models in the WebPage. Is foreign key best to do it? from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class schoolDetails(models.Model): sname = models.CharField(max_length=50) email = models.CharField(max_length=95) subdate = models.DateTimeField(default=timezone.now) username = models.CharField(max_length=100) principal = models.CharField(max_length=150, default='') address = models.CharField(max_length=100, default='Nepal') estdate = models.DateField(default=timezone.now) numstd = models.IntegerField(default=0) url = models.URLField(max_length=200, default='') password = models.CharField(max_length=95) def __str__(self): return self.sname class stdClass(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=95) ssname = models.CharField(max_length=95) cList = models.CharField(max_length=95) def __str__(self): return self.cList class stdDetails(models.Model): ondelete = models.ForeignKey(schoolDetails, on_delete=models.CASCADE) username = models.CharField(max_length=100) password = models.CharField(max_length=95) stname = models.CharField(max_length=150, null=True) ssname = models.CharField(max_length=150, null=True) stadd = models.CharField(max_length=150, null=False) stcls = models.CharField(max_length=150, null=True) stfname = models.CharField(max_length=150, null=True) stmname = models.CharField(max_length=150, null=True) stfo = models.CharField(max_length=150, null=True) stadate = models.DateField(default=timezone.now) stpnum = models.CharField(max_length=95, null=True) stbdate = models.DateField(default=timezone.now) stpht = models.ImageField(max_length=500, upload_to='') #(""), upload_to=None, height_field=None, width_field=None, def __str__(self): return self.stname #datetime.datetime(2020, 6, 25, 2, 33, 57, 858649, tzinfo=<UTC>) -
Returning optimised queryset based off of request.user for private comments
I currently have a comments model, whereby users can submit comments to our system "privately". This is set as a Boolean field on the model level, abridged version of the model as follows: class Comment(AbstractUUIDModel, AbstractTimestampedModel, VoteModel): class Meta: db_table = 'comments.Comment' indexes = [ models.Index(fields=['uuid', 'id']), ] verbose_name = 'Comment' verbose_name_plural = 'Comments' ordering = ['-created_datetime'] id = models.AutoField(_('ID'), primary_key=True) parent = models.ForeignKey('comments.Comment', null=True, blank=True, on_delete=models.CASCADE) owner = models.ForeignKey('authentication.User', null=True, on_delete=models.CASCADE) text = models.TextField(_('Description'), default='') private = models.BooleanField(_('Is Private?'), default=False) def __str__(self): return self.text def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) Essentially, the conceptual issue I am having is around my queryset filter logic. I want it such that if the request.user coming in to the system is the owner of the comment, then they can see their own "private" comments. Else, they can only see the comments where private is false. So, I need to somehow merge the following two querysets for serialization in DRF: queryset = obj.comment_set.filter(private=False) queryset = obj.comment_set.filter(owner=self.context.get('request').user) I believe I am overthinking this, and perhaps I can do something like: from django.db.models import Q queryset = obj.comment_set.filter( Q(owner=self.context.get('request').user) | Q(private=False) ) Using Q objects... -
Django url not working in one place despite same exact url working in the same page at other place
I am using a url at two different places but for some reason when the website contains only the first instance , it works perfectly but when I add another instance of the same link , the entire page is throwing error for some reason This is the part of the HTML page where I am using it : <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% for item in cat_menu %} <a class="dropdown-item" href="{% url 'category' post.category|slugify %}">{{ item }} </a> {% endfor %} </div> These are the two views involved in the link class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-post_date'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryView(request, cats): #change later to proper sluggify for better efficiency category_posts = Post.objects.filter(category=cats.replace('-',' ')) return render(request, 'category.html', {'cats': cats, 'category_posts': category_posts}) And this is the url path('Category/<str:cats>', CategoryView, name="category") Everythings seems to be completely correct but still for some reason I am getting the following error when I am trying to run the server Reverse for 'category' with arguments '('',)' not found. 1 pattern(s) tried: ['Category/(?P<cats>[^/]+)$'] Error during template rendering <a class="dropdown-item" href="{% url 'category' post.category|slugify %}">{{ item }} </a> … -
Share Django models between docker images
In my docker-compose there are a Django image and a independent python image for a script. I am trying to use the Models from the django application in the script, but I don't know how to import the models from one image to another. My docker-compose services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db service: build: context: . dockerfile: service_Dockerfile depends_on: - web ports: - "5555:5555" What could be the way to approach...? networks?? some image imports?? -
if cookie does not exist redirect user external url django
I have BaseContext view and other templateView. Token is created inside the template. I also checking the token cookie exists if not I redirect user to this url--> https://testdomain.com/get_token?origin=http://localhost:8000 class BaseContext(View): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) request = self.request if request.COOKIES.get('token') is not None: token = request.COOKIES.get('token') bla bla bla return context else: return HttpResponseRedirect('https://testdomain.com/get_token?origin=http://localhost:8000') and I have another view which inherited from basecontext class Services(BaseContext, TemplateView): template_name = "services.html" def get_context_data(self, **kwargs): request = self.request context = super().get_context_data(**kwargs) context.update({'service_active': 'Active'}) return context When I tried to load page, I got an error, like this, 'HttpResponseRedirect' object has no attribute 'update' -
How use Relative Url in html in Django?
Creating Django application , In Navbar there 3 anchor tags. When I write direct href="user/register" in Html file, it works for only first click. Getting url like http://127.0.0.1:8000/user/register/ from here if I click on any navbar link url is getting like http://127.0.0.1:8000/user/register/user/register or http://127.0.0.1:8000/user/register/login Have a look to code ProjectFolder/urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homePage, name = "homepage"), path('uploadFiles/', include("uploadFiles.urls")), path('user/', include("login.urls")), ] AppFolder.py/urls.py from django.urls import path from . import views urlpatterns = [ path("register/", views.register, name = "register") ] AppFolder/Views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def register(request): if request.method == "POST": return HttpResponse("Working on database") else: return render(request, "login/Register.html") Navbar.html <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="user/register">Register</a> </li> <li class="nav-item active"> <a class="nav-link" href="login">Log In <span class="sr-only">(current)</span></a> </li> </ul> </div> -
Get Django filter from an sql query
I want to convert this sql select query to a django filter query : "SELECT certiInst.* FROM bcs_certificate_instance certiInst LEFT JOIN bcs_certificate_instance certificateInstance ON (certiInst.certificate_id = certificateInstance.certificate_id AND certiInst.last_scan < certificateInstance.last_scan) WHERE certificateInstance.last_scan IS NULL ORDER BY last_scan DESC") Who knows the exact drf query to write please ... thanks -
TypeError: argument of type 'WindowsPath' is not iterable - in django python
whenever I run the server or executing any commands in the terminal this error is showing in the terminal. The server is running and the webpage is working fine but when I quit the server or run any commands(like python manage.py migrate) this error is showing. `Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 21, 2020 - 12:42:24 Django version 3.0, using settings 'djangoblog.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Python37\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Python37\lib\site-packages\django\utils\asyncio.py", line 24, in inner return func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable ` my manage.py file is provided below because the error mentioned something about manage.py file: #!/usr/bin/env python """Django's command-line utility for administrative … -
Integrating AWS Lambda with Django Signals and Postgresql RDS
I am wondering if I could trigger an AWS Lambda function using Django's post_save signal, or trigger an AWS Lambda function when a model is saved (just as Django's post_save signal does). Additionally, I would like to know some conventional ways of accessing and making changes to postgresql RDS in AWS Lambda functions. Any tips or suggestions will be greatly appreciated. Thank you! -
Wagtail settings only use .dev
I do not understand how to alternate between production and dev settings. Wagtail docs do not cover it and the only wagtail tutorial I can find mentions it and then completely skips over it. There is a settings file: --| settings ----| __init__.py ----| base.py ----| dev.py ----| production.py ----| .env my init file: import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) ENV = os.environ.get('AMSS_ENV') if ENV == 'dev': from .dev import * elif ENV == 'prod': from .production import * AMSS_ENV is set to 'prod'. I also have the DJANGO_SETTINGS_MODULE variable set to production in the .env from a different attempt. Does the init file not fire first? is my logic broken? I get no errors and everything works but it loads in dev every time. I've tried so many other things and it just sticks like this. Can someone tell me what am I supposed to do? or where I can look? -
pyodbc import error while using alpine image
I have below docker file FROM python:3.7-alpine # Create a group and user to run our app ARG APP_USER=appuser RUN addgroup -S ${APP_USER} && adduser -S ${APP_USER} -G ${APP_USER} RUN export CGO_ENABLED=0 RUN set -ex \ && RUN_DEPS=" \ pcre-dev \ shared-mime-info \ mariadb-dev \ nano \ busybox-extras \ curl \ " \ && seq 1 8 | xargs -I{} mkdir -p /usr/share/man/man{} \ && apk update && apk add --virtual buildups $RUN_DEPS \ && rm -rf /var/lib/apt/lists/* \ && apk del buildups # Copy odbc config file ADD odbcinst.ini /etc/odbcinst.ini # Copy in your requirements file ADD requirements.txt /requirements.txt RUN set -ex \ && BUILD_DEPS=" \ pcre-dev \ libpq \ gcc \ libc-dev \ g++ \ libffi-dev \ libxml2 \ unixodbc-dev \ build-base \ " \ && apk update && apk add --virtual buildups $BUILD_DEPS \ && apk update \ && pip install --no-cache-dir -r /requirements.txt \ \ && apk del $BUILD_DEPS \ && rm -rf /var/lib/apt/lists/* \ && apk del buildups RUN mkdir /code/ WORKDIR /code/ ADD . /code/ RUN chmod g+rx,o+rx / EXPOSE 8000 USER ${APP_USER}:${APP_USER} ENTRYPOINT ["/code/docker-entry-script.sh"] CMD ["runserver"] odbcinst.ini (checked inside container "Driver path and file is not there" [ODBC Driver 17 for SQL Server] … -
How to accept some of the form fields (not all) as CSV in Django?
I have a Django model with 2 fields as latitude and longitude. I've declared them both as a CharField. My model needs to accept more than 1 coordinates (latitude and longitude), so while entering in the rendered form (in the UI), I'm entering these coordinates separated by commas. It's this char input which I'm then splitting in the function and doing my computations.. This is my models.py class Location(models.Model): country = models.ForeignKey(Countries, on_delete=models.CASCADE) latitude = models.CharField(max_length=1000,help_text="Add the latitudes followed by comma or space") longitude = models.CharField(max_length=1000,help_text="Add the longitudes followed by comma or space") This is my view.py function def dashboard(request): form = LocationForm if request.method == 'POST': form = LocationForm(request.POST) if form.is_valid(): form.save() latitude = list(map(float, form.cleaned_data.get('latitude').split(','))) longitude = list(map(float, form.cleaned_data.get('longitude').split(','))) ......... ......... return render(request, dashboard/dashboard.html, { 'form':form }) Now, I want my model to accept the coordinates as a CSV file too. I want an option in the UI to add a csv file (having multiple latitudes and longitudes) which then populates these two char fields (as comma separated values). Note that, my csv file won't have the country name. I shall be entering the country using the form UI only. Thus, in short, I need to accept some … -
Is there any problem uploading django project to github without secret key?
I have pushed my Django project to Github and after some time I got a mail from GitGuardian saying my secret key is exposed and to protect my repo. Is there any problem exposing the secret key in your GitHub repo? And how do I hide the secret key?angoenter image description here -
Refused to display 'https://www.youtube.com/watch?v=-s7e_Fy6NRU&t=1761s' in a frame because it set 'X-Frame-Options' to 'sameorigin'
Well I am trying to play youtube videos on my site but i am having an issue. <p style ='text-align:center'> #if i enter directly link into src code it works fine. <iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe> #if i try to insert link from the data base it shows an error. <iframe width="640" height="390" src="{{all_videos.video_url}}" frameborder="0" allowfullscreen></iframe> </p> -
do postgresql has to be downloaded locally on venv or globally?
i'm a beginner to django and postgresql. currently i have the following directory structure for a django project python3.6 --> venv --> django_project .now , i want to install postgresql and psycopg2 and use it as a database . do i have to install it in venv with venv activated or install it in python3.6 folder. also how would the two installations above behave when i try to host the project on AWS ec2. i have installed postgresql in venv with venv activated and i'm getting the error 'NO module named psycopg2'. what did i do wrong? -
Request URL in Django error message does not correspond to the acual request url
I'm building an app with Django and Django-Rest-Framework. The frontend js application makes API calls to the backend. It works well when I test it using python manage.py ruserver but when i test it in a VM similar to my production environment, all API request get a 500 response. In the error message, the Request URL does not correspond to the actual request that was made. The actual request url looks like this: http://127.0.0.1:8080/api/account/login/ But the error message says it is something like this: http://127.0.0.1:8080/path/to/my/djoserapp/on/server/api/account/login/ The server is configured with nginx and daphne and the django version is 3.1 I don't know where to begin solving this and will greatly appreciate any help i could get. Thank you -
Javascript ID not showing reference to input text box - Django
{% extends 'halls/base.html' %} {% block content %} <div class="container"> <h2>Add Video to {{hall.title}}</h2> <form method="post"> {% csrf_token %} {% load widget_tweaks %} {% for field in form %} <div class="form-group {% if field.errors %} alert alert-danger {% endif %}"> {{ field.errors }} {{ field.label_tag }} {% render_field field class='form-control' %} </div> {% endfor %} <button type="submit" class="btn btn-primary"> Add</button> </form> <br> <h2>OR</h2> <form> {% for field in search_form %} <div class="form-group "> {{ field.errors }} {{ field.label_tag }} {% render_field field class='form-control' %} </div> {% endfor %} </form> <div id="search_results"></div> <script type="text/javascript"> var delayTimer; $("#id_search_term").keyup(function (){ clearTimeout(delayTimer); $('#search_results').text('Loadingggg'); }); </script> </div> {% endblock %} this is the HTML code. SO basically the whole idea here is when I inspect the search_form, it should give the id of the input box as "id_search_term". But when I inspect the box, it gives as id="id_search". I am not able to find a way to reference the input box with the ID in the script tag