Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validation of the serial number against the mask in Django rest
There are two tables - equipment type and equipment, the type has a line with a serial number mask, the equipment has a line with a serial number. When creating new equipment, validation must go through, that is, the string with the serial number is compared with each mask of the equipment type, and if a match is found, the equipment is tied to the type, the question is, how is it better to implement this on the django rest framework? The check is carried out according to the principle: N is a number from 0 to 9; A is a capital letter of the Latin alphabet; a is a lowercase letter of the Latin alphabet; X is a capital letter of the Latin alphabet or a number from 0 to 9; Z is a character from the list: “-“, “_”, “@” That is, if the equipment has a serial number of 0QWER9@123, it corresponds to a mask with characters like NAAAAXZXXX models.py from django.db import models from django.core.validators import MinLengthValidator from django.core.validators import RegexValidator class Type_Of_Equipment(models.Model): name = models.CharField(verbose_name='Тип оборудования', max_length=64, blank=True, default='Без названия') sn_mask = models.CharField(verbose_name='Маска серийного номера', blank=False, max_length=10, validators=[MinLengthValidator(10), RegexValidator(regex=r'^[NAaXZ]+$', message='Использованы недопустимые символы')]) class Equipment(models.Model): code … -
How can I submit Django forms without losing previously rendered HTML?
I am new to Django framework. I am trying to create a mini-project where my UI will have 3 html forms. The intended workflow is that I will submit a text in Input String field. Then I will submit some substrings of the above submitted string and increase the score. The problem I am having is when I submit the substring my page reloads and it resets the previously rendered html. Hence, I lose my actual string for which I am submitting substrings. The html code for Forms <div style="padding: 20px;"> <h1>Words Starting with consonants</h1> <form id="form2" action="consonant_submit/" method="post"> {% csrf_token %} <label for="Stuart">Stuart Text:</label> <input type="text" id="stuart" name="stuart"> <br> <label for="2">Stuart Score:</label> <input type="text" id="score1" name="score1"> <br> <input type="submit" value="Submit stuart"> </form> </div> <div style="padding: 20px;"> <h1>Words Starting with consonants</h1> <form id="form3" action="vowel_submit/" method="post"> {% csrf_token %} <label for="kevin">Kevin Text:</label> <input type="text" id="kevin" name="kevin"> <br> <label for="2">Kevin Score:</label> <input type="text" id="score2" name="score2"> <br> <input type="submit" value="Submit kevin"> </form> </div> The consonant_submit & are django view functions. I am attaching my sample urls.py and sample views.py Urls.py from django.urls import path from . import views urlpatterns = [ path("",views.index,name="index"), path('consonant_submit/', views.consonant_submit, name='consonant_submit'), path('vowel_submit/', views.vowel_submit, name='vowel_submit'), ] And views.py from django.shortcuts … -
python - How to update multiple dictionary key-value without using for loop
I have a list of dictionaries with the same keys but different values. Example: [{ Price = 100; Quantity = 3; }, { Price = 200; Quantity = 5; }] Is there a way to update the value of a particular key in all dictionaries in one go without using for loop? That is, is there a way to make Quantity=0 for all dictionaries in the list in one go? I am looking for performance since I have a huge list of dictionaries, and I'm under the assumption that there may be a faster way to do this than using a for loop. I have. gone through multiple questions on stack overflow but did not get any satisfactory response. -
send selected date to django using htmx & pickadate.js
I use the pickadate.js widget, to select a date. The selected date should be sent to django do query availability. pickadate.js creates a hidden input field with name="date_submit". I use jQuery to add some htmx attributes to listen on the change event of that element. That works so far and the hidden input element has all the necessary hx-attributes assigned to it. I debugged the events with htmx.logAll();. the 'change' event is fired on the element. However, the hx-attributes on the hidden input field don't have any effect and no requests are made to the django backend. The code is part of a form, placed in a modal. rendered hidden input field: <input type="hidden" name="date_submit" value="2023-05-26" hx-trigger="change" hx-get="/" hx-target="#test"> Date Formfield: <div class="form-floating"> {% render_field reservation_form.date class="datepicker form-control mb-3" %} <label for="{{ reservation_form.date.id_for_label }}">Event Date</label> </div> Script: <script> htmx.logAll(); var $input = $('.datepicker').pickadate({ format: 'yyyy-mm-dd', formatSubmit: 'yyyy-mm-dd', min: 0, max: 90, disable: {{ blocked_dates }}, firstDay: 1, onOpen: function() { // Get the hidden input field var hiddenInput = $(this.$node).siblings('[name="date_submit"]'); // Add HTMX attributes to the hidden input field hiddenInput.attr('hx-trigger', 'change'); hiddenInput.attr('hx-get', "{% url 'home' %}"); hiddenInput.attr('hx-target', '#test'); } }); $input.on('change', function() var hiddenInput = $(this).siblings('[name="date_submit"]'); hiddenInput.val($(this).val()); htmx.trigger(hiddenInput[0], 'change'); }); … -
How can I use keyple API to emulate a badge for accessing university buildings with NFC-enabled smartphones?
I'm working on a project which purpose is to emulate a badge using calypso protocol on a smartphone (with an NFC chip) via website (eg django) or an android application in order to access university buildings without the badge but only with the phone. I'm looking for some information on internet and I discovered that there are keyple api but I'm not sure if it works for my job. The question is: keyple api are ok for my aim? If so, it's better to develop a website or an android app? -
Auto start Nginx and Gunicorn in Docker
I am a student, and I am currently trying to deploy my Django application on Docker Ubuntu using Nginx and Gunicorn. However, when I restart the container, both Nginx and Gunicorn are also turned off. I have to use the command "docker attach " to enter the container and run the commands service nginx start and systemctl start gunicorn. Is there any way to automatically start Nginx and Gunicorn when the container is restarted? Thank you sincerely. [This is the configuration file.](https://i.stack.imgur.com/HC7Ol.png) I have tried writing a start.sh file like this: #!/bin/bash # Start Nginx service nginx start # Start Gunicorn systemctl start gunicorn exec "$@" and Dockerfile FROM my_image COPY start.sh /start.sh RUN chmod +x /start.sh EXPOSE 80 CMD ["/start.sh"] -
The best technology for chat in django, Django-channels, FastAPI, FlaskSockerIO, Tornado and others [closed]
I want to create a chat in my django app. Which technology should I choose? Many people write that django-channels is bad, so I would like to know your opinion Sorry if this question was asked, but unfortunately I didn't find it -
Select element options not opening on first click with Bootstrap
I have a html template with four selects. The same thing happens to me in all four. When I click on the select the first time it doesn't open, but after that, the following times it does. I want the options to be open the first time too. Los selects son así: <div class="input-group"> <select class="selectpicker" multiple data-live-search="true" id="src" name="src"> {% for value, label in jobs%} <option value="{{ value }}">{{ label }}</option> {% endfor %} </select> </div> The javaScript part is this. I have tried to do it in many ways but I can't. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script> <script> // Wait for the DOM to be ready document.addEventListener("DOMContentLoaded", function() { // Select all <select> elements var selectElements = document.querySelectorAll("select"); // Apply the Bootstrap Select plugin to each <select> element selectElements.forEach(function(selectElement) { console.log("DOM ready"); new bootstrap.Select(selectElement); }); }); </script> -
I inherited AbstractBaseUser, but my password is saved in plain text
My model is as follows. class Student(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, blank=True) id = models.CharField(max_length=10, primary_key=True) date_of_birth = models.DateField() gender = models.CharField(max_length=10) student_type = models.CharField(max_length=50) bio = models.TextField() email = models.EmailField(blank=False) phone = models.CharField(max_length=20, blank=False) is_selected = models.BooleanField(default=False) select_limit = models.PositiveIntegerField(default=0) select_count = models.PositiveIntegerField(default=0) groups = models.ManyToManyField(Group, related_name='%(class)s_groups') user_permissions = models.ManyToManyField(Permission, related_name='%(class)s_user_permissions') photo = models.ImageField(upload_to='student_photo/', default='student_photo/student_photo.png') USERNAME_FIELD = 'id' The results of my model creation are as follows enter image description here I hope my password is stored as ciphertext, so how can I solve it -
Displaying objects of several users in Django
I am coding network site and it has "Follow/Unfollow" function. When user follows X,Y users, there are following tab in the nav bar. There should be displayed all the posts of X,Y users the user has followed. Here is the view function: def following(request): currentUser = request.user users = currentUser.following.all() #Getting all the users the currentUser is followed to context = {"posts": postsOfFollowedUsers} return render(request, "network/following.html", context) How do I display all the posts related to several users? -
Deploying Angular-Django app on Hetzner Cloud - Cost-effective infrastructure for building scalable applications
I am looking to deploy my Angular-Django app on Hetzner Cloud and would like to get some insights and recommendations regarding the best practices and tools to use in this setup. I have chosen Hetzner Cloud for its cost-effectiveness and the need to build a scalable infrastructure for my application. Here's an overview of my deployment requirements and the technologies I am working with: Angular: Frontend framework for building the user interface. Django: Backend framework for implementing the business logic and API endpoints. PostgreSQL: Database management system for storing application data. Docker: Containerization technology for packaging my application and its dependencies. Nginx: Web server and reverse proxy for serving static files and routing requests. My goal is to achieve a reliable and scalable deployment, optimizing performance and minimizing costs. Specifically, I have the following questions: What is the recommended approach for deploying an Angular-Django app on Hetzner Cloud? Are there any specific tools or frameworks that work well in this setup? How can I leverage Docker for containerizing my application and managing its dependencies? Are there any best practices or considerations I should keep in mind? What is the suggested database setup for Django on Hetzner Cloud? Should I use … -
Django returns corrupted zip file
I wrote following code which fetches a data from db, forms two csvs, creates a zip containing both csvs and saves it to file system: import csv import io import zipfile from django.db import connection from models import MyModel myVal = 1019 with connection.cursor() as cursor: cursor.execute('''query''') query_result = cursor.fetchall() all_rows_result = MyModel.objects.filter(col1=myValue) # Create the zip file in memory zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w') as zip_file: # Create the query result CSV query_data_csv = io.StringIO() query_data_writer = csv.writer(query_data_csv) query_data_writer.writerow(['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) for row in query_result: query_data_writer.writerow(list(row)) zip_file.writestr('query_result.csv', query_data_csv.getvalue()) # Create the all rows CSV all_rows_csv = io.StringIO() all_rows_writer = csv.writer(all_rows_csv) all_rows_writer.writerow(['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) for row in all_rows_result: all_rows_writer.writerow([row.id, row.course_id, row.url, row.ip_address, row.date_visited, row.user_id]) zip_file.writestr('all_rows.csv', all_rows_csv.getvalue()) with open('data.zip', 'wb') as zip_output: zip_output.write(zip_buffer.getvalue()) I ran above function and opened data.zip file. It contained two csv with desired data. The zip size was 4.1 kB. But when I opened, it shows one csv of size 2.0 kB and other of size 1.9 kB. Then, I converted this to django REST endpoint: import csv import io import zipfile from django.db import connection from models import MyModel from django.http import HttpResponse def get_user_tracking(request): myVal = request.GET.get('my_val') with … -
How can I annotate a calculated field into a Django queryset?
How can I get a calculated field into a queryset? Here is a code snipped: models.py: class Test(models.Model): field1 = models.CharField() @property def calc_field(self): return "hi" views.py: test = Test.objects.all() print(test[0].calc_field) # this works, but only in the backend test1 = Test.objects.all().values_list() print(test[0].calc_field) # this doesn't work, but this is what I get in the frontend If I pass this data to the frontend (Vue via Inertia) I can't access the calc_field anymore. Does anyone know how I can annotate the calc_field to the queryset? -
how to access a django sqlite3 database from command line?
I'm using an sqlite3 database for a django app, and it works correctly. I can print the version used with this code i wrote inside a view: # views.py import sqlite3 def my_view(..): connection = sqlite3.connect('C:/path/to/db.sqlite3') cursor = connection.cursor() cursor.execute('SELECT sqlite_version();') result = cursor.fetchone() sqlite_version = result[0] print("SQLite version:", sqlite_version) ... But if i run from command line python manage.py dbshell i get CommandError: You appear not to have the 'sqlite3' program installed or on your path. There are similar questions but the answers for example suggests to download sqlite3 which i don't think it makes sense because I can see that I already have a version installed Using: Django 4.2, Python 3.10.4, sqlite3 3.37.2. In a virtual environment. -
Access to XMLHttpRequest at 'http://localhost/api/get/' from origin 'http://localhost:3002' has been blocked by CORS policy in Django
I am trying to connect Django and React, I made an API in Django and calling that api from React app. But I am getting Access to XMLHttpRequest at 'http://localhost/api/get/' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I know there are lots question on this topic, but none of those seem to solve in my case This is my settings.py file from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-(!kg*t#pzv!q6%xgap@)wg)dm8@lrtmh2x&f5yf5u15p7tmoc5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'analyzer_util.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'analyzer_util.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases … -
What do i set my STATIC_ROOT to when using django-storages, boto, boto3?
I am using linode object storage and django project deployed on a linode server. I have everything set up as far as the linode bucket and aws settings in my settings.py but what do I set my static_root to? STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage" }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage" }, } LINODE_BUCKET = "my_bucket" LINODE_BUCKET_REGION = "us-east-1" AWS_S3_ENDPOINT_URL = f"https://{LINODE_BUCKET_REGION}.linodeobjects.com" -
Render Error: Cannot read property 'isLoggedIn' of undefined
I'm working with react native as front end and django as backend to create an app using expo. i'm using expo go which means i'm creating it directly on my mobile phone. the issue is my front end cannot read my backend api i get a render error that says: cannot read property 'isLoggedIn' of undefined. i've been stuck on this for 3 days i don't know what to do. i will appreciate every suggestions. `import React, { useState, useEffect, useRef, createContext } from "react"; import { SafeAreaProvider } from 'react-native-safe-area-context'; import Navigator from "../navigation/navigator"; const Context = createContext() const Provider = () => { const [ domain, setDomain] = useState("http://192.168.27.95:8000") const [ isLoggedIn, setIsLoggedIn ] = useState(false) const [ appSettings, setAppSettings ] = useState({}) function initAppSettings() { fetch(`${domain}/api/v1.0/app/settings`, { method: 'GET' }) .then(res => { if (res.ok){ return res.json() } else { throw res.json() } }) .then(json => { setAppSettings(json) }) .catch(error => { console.log(error) }) } useEffect(() => { initAppSettings() }, []) const globalContext = { domain, isLoggedIn, setIsLoggedIn, appSettings, setAppSettings, } return <Context.Provider value={globalContext}><SafeAreaProvider><Navigator /></SafeAreaProvider></Context.Provider> }; export { Context, Provider }; ` -
Django: Save inline form before run action
I'm using a django-inline-actions package for let end-users run actions in admin inlines. But it's no matter what exactly using for action button, i can implement it by hand (like this, for example), behavior will still the same. This look as: As provided by the django engine, the user does things like: Fill inline Click Save and continue button Click action button and he repeating it again and again, becouse users use action buttons very often. Is there any possibility for omit step 2? I think, it can be javascript hook, which capture click event, save inline data with ajax, and then run action. But i have no idea how implement it. May be there is another way to do it? -
Generate access token without code challenge and code verifier, with django rest along django-oauth-toolkit for OAuth access
I am trying to generate the access_token and refresh_token with Django rest framework and django-oauth-toolkit lib for the OAuth access delegation. I am trying to delegate the access to third party platform, where the third-party platform display the login button and when a user clicks the button it will open my website with response_type, client_id, scope, and redirect_uri. (all of these variable will be set on the third-party platform while setup). As per the django-oauth-toolkit documentation we also need to pass the code_challenge and code_challenge_method in the url while opening the login link, but third-party platform does not pass these 2 variables in the request. As per this documentations I am tryed by setting the PKCE_REQUIRED=False in the setting file of the project but getting an error of code_challenge in the response. Request URL http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=bG2Ju69XwS8jvnx3CWiobmWi1dj4kWsNYSiVsXEa&redirect_uri=http://127.0.0.1:8000/code/redirect/ Response http://127.0.0.1:8000/code/redirect/?error=invalid_request&error_description=Code+challenge+required. The authentication functionality is working with the code_challenge in the URL and able to generate the authorization_code Working example Request URL http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=bG2Ju69XwS8jvnx3CWiobmWi1dj4kWsNYSiVsXEa&redirect_uri=http://127.0.0.1:8000/code/redirect/&code_challenge=yCo4U9wZJPeYGyX3F6df_heuxG-6ZnvZfZB5KrCYpp4&code_challenge_method=S256 Response http://127.0.0.1:8000/code/redirect/?code=EAwEXghF807RTjxwyohky8psQKGohP I also tried with the OAUTH2_USE_PKCE = False in the setting file but not working. Thanks :) -
How can I resolve a 'MultipleObjectsReturned' error when integrating Razorpay payment in a Python Django application?
we integrated razor pay payment gateway our python Django application while making payment getting beloow error - MultipleObjectsReturned at /paymenthandler/abcd@gmail.com/2/ get() returned more than one book_history -- it returned 5! Request Method: POST Request URL: http://spandiagno.com/paymenthandler/abcd@gmail.com/2/ Django Version: 4.0.5 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one book_history -- it returned 5! Exception Location: /home/ubuntu/main/span_diagno/venv/lib/python3.10/site-packages/django/db/models/query.py, line 499, in get Python Executable: /home/ubuntu/main/span_diagno/venv/bin/python3 Python Version: 3.10.6 Expected to fix payment issue in razorpay. -
How to implement OpenID Connect with JWT id_token in Django allauth?
i use allauth Plugin for Django. I would like to give the users the possibility to log in to another provider. This offers OpenID Connect with JWT id_token. Can I solve this with allauth onboard or do I need my own provider? The goal is to register with this Provider and also login if the user is registered. With Google, Facebook ect. This works. i try to use openid_connect provider from allauth, but this is not JWT -
upload files to another shared hosting, with django
i have a django shared hosting(cpanel), but for storaging files coming from Front-end, i needed more space so i got an another shared-hosting(direct-admin) to upload files there, i connected the shared-hosting-storage to django-shared-hosting as a sub domain(in capnel with ip in ZoneEditor), like: http://dl.sabaol.ir, but i dont know how to upload files with django from django-shared-hosting to my shared-hosting-storage coming from front-end,i hope u guys to understand what i said :/ i googled so much about that , some said use ftp, is it right? if it is, but how? -
How do i Filtering the products by category using Ajax in django template
Here I'm trying to filter the products by category so I'm using the Ajax. So my problem is I have one shopt.html page in that page I filter the category that is displayed list wise and I click the radio button for the corresponding category I want to display the category-wise product... Model class Category(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE) name = models.CharField(max_length=100) View def filter_data(request): categories = request.GET.getlist('category[]') brands = request.GET.getlist('brand[]') allProducts = Product.objects.all().order_by('-id').distinct() if len(categories) > 0: allProducts = allProducts.filter(Categories__id__in=categories).distinct() if len(brands) > 0: allProducts = allProducts.filter(Brand__id__in=brands).distinct() t = render_to_string('ajax/shop.html', {'product': allProducts}) return JsonResponse({'data': t}) Here I'm trying to filter the products by category so I'm using the Ajax. So my problem is I have one shopt.html page in that page I filter the category that is displayed list wise and I click the radio button for the corresponding category I want to display the category-wise product... HTML <script> $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ var filter_object={}; $(".filter-checkbox").each(function(index,ele){ var filter_value=$(this).val(); var filter_key=$(this).data('filter'); console.log(filter_key,filter_value); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'{% url "filter-data" %}', data:filter_object, dataType:'json', success:function(res){ $("#filteredProducts").html(res.data); } }); }); }); {% endblock %} <form action="#"> {% for i in category %} <div class="single-widget-category"> <input type="checkbox" data-filter="category" id="{{i.id}}" value="{{i.id}}" class="filter-checkbox"> <label for="{{i.id}}">{{i.name}}<span>{{i.product_set.all.count}}</span></label> … -
How can I fix the AssertionError in my Django test case for image path generation in models?
I have created test case for generating the image path and added the function in the models for generating the image path I got the following error AssertionError: 'uploads\recipe\test-uuid.jpg' != 'uploads/recipe/test-uuid.jpg' uploads\recipe\test-uuid.jpg ? ^ ^ uploads/recipe/test-uuid.jpg ? ^ ^ @patch('core.models.uuid.uuid4') def test_recipe_file_name_uuid(self,mock_uuid): '''test generating image path''' uuid="test-uuid" mock_uuid.return_value=uuid file_path=models.recipe_image_file_path(None,"example.jpg") self.assertEqual(file_path,f'uploads/recipe/{uuid}.jpg') and the recipe_image_file_path in the models file is as follows def recipe_image_file_path(instance,filename): '''generating a file path for the new recipe image''' ext=os.path.splitext(filename)[1] filename=f'{uuid.uuid4()}{ext}' return os.path.join('uploads','recipe',filename) When I run test case I want to match the assertEqual(file_path,f'uploads/recipe/{uuid}.jpg') -
Why am I getting a Could not parse the remainder error when using AJAX with Django templates?
Here is my code using ajax in my code View def filter_data(request): categories = request.GET.getlist('category[]') brands = request.GET.getlist('brand[]') allProducts = Product.objects.all().order_by('-id').distinct() if len(categories) > 0: allProducts = allProducts.filter(Categories__id__in=categories).distinct() if len(brands) > 0: allProducts = allProducts.filter(Brand__id__in=brands).distinct() t = render_to_string('ajax/shop.html', {'product': allProducts}) return JsonResponse({'data': t}) Adding script to the HTML file {% block script%} <script> $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ var filter_object={}; $(".filter-checkbox").each(function(index,ele){ var filter_value=$(this).val(); var filter_key=$(this).data('filter'); console.log(filter_key,filter_value); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'{% url filter-data %}', data:filter_object, dataType:'json', success:function(res){ $("#filteredProducts").html(res.data); } }); }); }); </script> {% endblock %} URL path('shop/filter-data',filter_data,name='filter-data'), Got an unexpected eeror Error during template rendering Could not parse the remainder: '-data' from 'filter-data' url:'{% url filter-data %}' Got an error in my script tag So i changed the url to following the below code $.ajax({ url:'{% url 'filter-data' %}', data:filter_object, dataType:'json', success:function(res){ $("#filteredProducts").html(res.data); but got an error in the HTML file please check the below image Error image