Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run a "always on" redis keyspace event listener with django
I have deployed a django application on an EC2 instance. I have used NGINX as the reverse proxy and gunicorn as the WSGI server to serve requests from the django app. As part of a functionality within the app, I want to listen to redis keyspace notifications on expiry of certain keys (which match a given pattern) and upon receiving the expiry event, perform something (write something to the database). This would require a piece of code (redis-listener) to be constantly running alongside my django app to listen to any incoming redis event. I am not able to arrive at an optimal implementation for this listener. One approach is that I can use threading to run the listener in a separate thread than the main django app thread (by running the listener in a new thread inside the ready() method) but then for each incoming request, gunicorn will create or assign a new worker process with its own instance of the django app and the listener thread. So, I end up running as many redis listener threads as there are active incoming requests. And each redis event will be effectively listened multiple times simultaneously, which is not what I want. … -
Using fuzz.ratio on Django object field confusion
I think this is a simple issue but I'm a little confused on the syntax for doing this. I have a Django model called Sentence which is exactly what it sounds like, just the text of a single sentence (related to a location model but that is irrelevant for this). Here is the model: class Sentence(models.Model): location = models.ForeignKey( Location, related_name="sentences", on_delete=models.CASCADE ) text = models.TextField() def __str__(self): return self.text In a view in views.py related to this model, I first filter so only sentences that contain words from a user query are kept. queryset = Sentence.objects.filter(text_icontains=query) I want to then sort these sentences in the queryset by a score given to them in relation to a query from the user using fuzz ratios (assume query is already established to be a string): queryset = queryset.annotate(score=fuzz.partial_ratio(query, '[CONFUSED HERE]')).order_by('-score') but I am having trouble figuring out how to compare this string query from the user to the text within each of the sentence objects, if that is something that is possible. Ideally, this would make the queryset be ordered by this fuzz ratio so the first value in the queryset is the sentence with the highest match to the user's query. … -
How to serialize two related models in Django
I have two model: class Liver_Function_Tests(models.Model): blood_lab=models.ForeignKey(Blood_Lab,on_delete=models.CASCADE,null=True, related_name='liver_function_tests') class Blood_Lab(models.Model): patient=models.ForeignKey(Patient,on_delete=models.CASCADE,null=True) I have created serializer for Liver_Function_Tests model class Liver_Function_Tests_Serializer(serializers.ModelSerializer): class Meta: model=Liver_Function_Tests fields = '__all__' Now, I need to include this serializer into Blood_Lab_Serializer class Blood_Lab_Serializer(serializers.ModelSerializer): liver_function_tests_details = Liver_Function_Tests_Serializer(source='liver_function_tests.last', required=False) class Meta: model=Blood_Lab fields = ['id','patient', 'liver_function_tests_details'] The problem is, when creating Blood_Lab I have to assign the blood_lab forign_key that is not created yet, http://127.0.0.1:8000/api/bloodlap/ What is possible solutions to this problem ? -
Randomly select from database using datetime in Python Django
I am making a project in Django right now that needs to select a daily item from the database (it's like a Wordle type of project). I have a database of 100 items and I want every user who visits the site to see the same daily item. I tried to do some logic of converting a date to an integer to index the database, but it got clunky and I figured there must be a better way to do this. The goal is to select from the database based on datetime.now and have it return one unique row. After the database has been used up it will just reset and start over again. I also considered having a daily job run every day to update the database with a 'todaysItem' flag but I don't think that is the best solution. -
Django: how to get a URL view name from a request?
In Django url configs, you can use url "view names" to aid various activities like redirects. Seen here in this example urls.py file (the final name arguments): urlpatterns = [ path('', views.home_view, name='home'), path('search/', views.search_view, name='search'), .... Now, in my Django view function, I would like to inspect the current request object to discover the current url "view name" for the current request. This could be useful to create a general-purpose "handler" function that could be called from multiple views (or better yet to use in a view decorator). This would allow your general purpose function to redirect to the current page on a POST request for example. But to redirect via redirect() requires knowing the "view name" you want to redirect to. How can I find the "view name" by inspecting the current request? -
checkbox becomes unchecked when another checkbox becomes checked django
I have two checkboxes , in two different HTML forms. In my template , i made that when a checkbox is clicked , its value gets submitted to the view function and saved to the database and then that checkbox becomes an icon using an if else statement. Like that: <form id='ISBN_form' action="{%url 'tracker:bookSteps' book_page.id%}" method="POST"> {% csrf_token %} <div class="columns is-mobile"> {% if book_progress.ISBNsent == 'True' %} <div class="content column is-5"> <label class="checkbox" dir="rtl"> <i class="fa-solid fa-check has-text-success"></i> تم التسليم </label> </div> {%else%} <div class="content column is-5"> <label class="checkbox" dir="rtl"> <input type="checkbox" name="ISBNsent" id="ISBNsent" value="True" onchange="submitCheckbox();"> تم التسليم </label> </div> {%endif%} </form> That works great and the value gets saved to database and it becomes an icon in the html page. But the problem is that when i check a checkbox the other one becomes unchecked and vice versa , only in the html template but in the database it stays checked. I don't know where the problem is and why this behavior is happening while i have the if else and the value that is being checked is from the database so why it gets unchecked again? my view function: def bookSteps(request,book_id): book_page = get_object_or_404(Book, pk=book_id) print(book_page.id) book_progress … -
How do i change translation values in Django wagtail?
How can I change some of the translations in wagtail which I don't like (or add new ones)? My first attempt was to change values in the wagtail/locale/{language-code}/django.po files, then to recompile them in .mo files, hoping to change translations, but this didn't work. Image -
Django library upload
not taking the created module and shows error enter image description here I am creating a website through django but when i tried to push data in the database it shows error in taking the module. And when i changed the name in module then it shows duplicate names mot allowed. enter image description here Github Repo link: https://github.com/Prakhar2706/Django_first_project -
Python and Django: How do I dynamically create a dynamic URL with employee ID
I have a specific template that can filter an activity logs of an Employee. This is my view: @login_required def activity_filter(request, buyer_id): """Returns activities based on the filter options sent by an (AJAX) POST.""" template_name = 'buyer/activity/activities.html' activities = _compile_activities(request.user.cached_buyer, request.user.cached_buyer_role.privacy_filter) year_range = list(range(activities[0].date_created.year, activities[len(activities) - 1].date_created.year - 1, -1)) form = _ActivitiesFilterForm( buyer_id=buyer_id, data=request.POST, user_choices=_compile_activity_users(activities), from_date=activities[len(activities) - 1].date_created, to_date=activities[0].date_created, from_to_year_range=year_range, ) if not form.is_valid(): _logger.debug("Filter validation errors: %r", form.errors) return render(request, template_name, status=400) query_params = getattr(request, request.method) # either the request.GET or request.POST dict from_date = query_params.get('from_date', None) if from_date: from_date = datetime.combine(from_date, datetime.min.time()) # first second of the day activities = activities.filter(date_created__gte=from_date) to_date = query_params.get('to_date', None) if to_date: to_date = datetime.combine(to_date, datetime.max.time()) # last second of the day activities = activities.filter(date_created__lte=to_date) selected_users = query_params.getlist('users', None) if selected_users: user_role_ids, user_role_types = _get_selected_user_role_details(selected_users) if user_role_types and user_role_ids: activities = activities.filter(user_role_type__in=user_role_types).filter(user_role_id__in=user_role_ids) if ( query_params.getlist('users') ): print("===selected_users===\n", query_params, "\n===selected_users===\n") context = { 'activities': activities[:MAX_NO_OF_ACTIVITIES], 'activities_search_form': form, } if is_ajax(request): return render(request, 'buyer/activity/activities_table.html', context) return render(request, template_name, context) <a href="{% url 'buyer:activity' employee.buyer_id %}"> {% svg_icon "Activity" "w-6 h-6 dui-stroke-primary" None "Latest Activity" %} </a> But I need this icon(URL) <a> tag once clicked it will redirect and automatically filtered on my Latest … -
NotFittedError at /classify/ Vocabulary not fitted or provided
I am trying to build a spam classifier. However, when sending a POST request, I am getting the error "NotFittedError: Vocabulary not fitted or provided". How can I solve this issue? My POST request looks: { "email":"Get free v-bucks. For that click on link https:/rk%jgqk@$bjg&kjraekj/youRickRolledXD" } Here my code in models.py file nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('punkt') try: wordnet.ensure_loaded() except LookupError: nltk.download('wordnet') class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear1 = nn.Linear(10000, 100) self.linear2 = nn.Linear(100, 10) self.linear3 = nn.Linear(10, 2) def forward(self, x): x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x def classify_spam(message): model = LogisticRegression() model.load_state_dict(torch.load('W:/SpamOrHamProject/SpamOrHamBack/api/AIModel/SpamClassification.pth')) model.eval() cv = CountVectorizer(max_features=10000, stop_words='english') processed_message = preprocess_message(message) vectorized_message = cv.transform([processed_message]).toarray() with torch.no_grad(): tensor_message = Variable(torch.from_numpy(vectorized_message)).float() output = model(tensor_message) _, predicted_label = torch.max(output, 1) return 'Spam' if predicted_label.items() == 1 else 'Not Spam' def preprocess_message(message): remove_non_alphabets = lambda x: re.sub(r'[^a-zA-Z]', ' ', x) tokenize = lambda x: word_tokenize(x) ps = PorterStemmer() stem = lambda w: [ps.stem(x) for x in w] lemmatizer = WordNetLemmatizer() leammtizer = lambda x: [lemmatizer.lemmatize(word) for word in x] processed_message = remove_non_alphabets(message) processed_message = tokenize(processed_message) processed_message = stem(processed_message) processed_message = leammtizer(processed_message) processed_message = ' '.join(processed_message) return processed_message And there code for my trained model: nltk.download("wordnet", "W:/SpamOrHamProject/SpamOrHamModel/nltk_data") os.listdir(r"W:/SpamOrHamProject/SpamOrHamModel/input/") data = … -
Django threading behind IIS and wfastcgi
I have a Django application that executes a lengthy task, that is controlled by Ajax on one of the app's pages. The first Ajax call creates an entry in a task table in the db, and then creates a thread that executes that task, by calling a Java app via Py4J. This sends a command to a legacy server and then regularly queries it for status and updates the task table until the task is complete. The code is as follows: # Get a PyFJ command def getMCLCmd(): gateway = JavaGateway() try: cmd = gateway.entry_point.getMCLCmd() return cmd except Py4JNetworkError as e: # maybe server not started logger.info('Py4J not started, starting it') pyserver = py4JVM() pyserver.start() # try again try: cmd = gateway.entry_point.getMCLCmd() return cmd except Py4JNetworkError as e: logger.debug('Py4J error' + e) return None class py4JVM(threading.Thread): def __init__(self): threading.Thread.__init__(self, daemon=True) self.error = None def run(self): try: process = subprocess.run(MCL_CMD, shell=True, check=True, stdout=subprocess.PIPE, universal_newlines=True) output = process.stdout logger.info(f'Py4J output: {output}') except subprocess.CalledProcessError as e: self.error = f"command return with error (code {e.returncode}): {e.output}" logger.error(self.error) # the thread class class FirstInitThread(threading.Thread): def __init__(self, task: ClientTask): self.task = task threading.Thread.__init__(self) def run(self): cmd = getMCLCmd() if cmd is None: self.task.status = 0 self.task.status_msg … -
Why is my Bootstrap checkbox always checked?
I'm using django-bootstrap for my Django project. A user of the website can create/update his posts, where one of the fields is Boolean field(is_public). The problem is, even when the user saved Boolean field as False, when he enters the update page the checkbox is checked. I first thought the data is not properly saved or passed to template, but it turns out it's not the case. Nothing is wrong with the backend logic. I checked this in my template. {{form.is_public}} Can be public. {{form.is_public.value}} <!-- Gives "False" which is correct --> So to wrap up, the value is passed correctly, but the checkbox is always checked by default. How do I solve this problem? -
Django SQLITE database showing wrong column names
from django.db import models class Players(models.Model): name = models.TextField() role = models.TextField(default="role") salary = models.DecimalField(decimal_places=2,max_digits=4) team = models.TextField() Actual CSV FILE SQLITE Table created on Django I am importing a csv file into a SQLITE table on Django, which I have attached below. This is the code I have written in the models.py fil to create the table. However, the SQLITE table created (attached below) has the column names in the wrong order. -
Django showing incorrect url but displaying the correct content
I am having an issue with some Django code; I have a form at mysite/edit_home, which updates some content which will be displayed on the index page at the root of mysite/. When the form correctly submits, it renders the index template, and all content is correctly displayed, but the url does not change, and instead shows /mysite/edit_home still despite showing a different page. I'm wondering if there's any reason why this will not change? I have tried to remove as much information from the below as it is a pretty large site already so don't want to clutter the issue. There are no issues other than this across all the other pages and databasing, etc, and this issue only is showing the wrong url and does not affect the content of the page. Thanks for all the help. I have tried most combinations of changing urls files, and changing the method of rendering, ie using a reverse etc but it won't say anything besides /mysite/edit_home rather than /mysite/ or /. Below is the code: mysite/project/urls.py urlpatterns = [ path('mysite/', include('mysite.urls')), path('admin/', admin.site.urls), path('', views.index, name='index') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) mysite/urls.py from django.urls import path ... app_name = 'mysite' urlpatterns … -
countdown timer Django
need to implement a timer with the following idea: the user has a form to submit their data to the Answer database, which is handled by the QuizTake class. This class contains views that perform various functions such as validation, user authentication, data submission to the server, and data saving. The functionality you want to implement is as follows: create a countdown function where, while the timer is running, the answer submission form is enabled and the user can use it. When the timer expires, the form saves its content and forcefully saves it to the Answer database, and input into the form is no longer accessible. How can this be implemented? view class QuizTake(FormView): form_class = QuestionForm template_name = 'cansole/question.html' result_template_name = 'result.html' single_complete_template_name = 'single_complete.html' timer_duration = 3600 def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() ##сделать редирект на логин if self.sitting is False: return render(request, self.single_complete_template_name) self.start_time = datetime.now() self.timer_expired = False return super().dispatch(request, *args, **kwargs) def check_timer_expired(self): elapsed_time = (datetime.now() - self.start_time).total_seconds() return elapsed_time >= self.timer_duration def get_form(self, *args, **kwargs): if self.logged_in_user: self.question = self.sitting.get_first_question() … -
<a> tag concatonates current url to href value in django
Im building an app where users can enter their twitter, fb and ig account links to their profiles. After they have submitted these urls to the profile form my django app save them to db and later on these values should be populated in the profile page as tags as such. <div class="gap-3 mt-3 icons d-flex flex-row justify-content-center align-items-center"> {% if object.twitter_link %} <a href="{{ object.twitter_link }}"><span><i class="fa fa-twitter"></i></span></a> {% endif %} {% if object.fb_link %} <a href="{{ object.fb_link }}"><span><i class="fa fa-facebook-f"></i></span></a> {% endif %} {% if object.ig_link %} <a href="{{ object.ig_link }}"><span><i class="fa fa-instagram"></i></span></a> {% endif %} </div> I noticed that the tag values are not the same as in the href attribute. For example these are the actual values of the href attribute and the corresponding tag values. {{ object.twitter_link }} = 'weeeee' --> https://currentpageurl.com/weeeee {{ object.fb_link }} = 'www.facebook.com' --> https://currentpageurl.com/www.facebook.com {{ object.ig_link }} = 'https://www.instagram.com/instagram/' --> https://www.instagram.com/instagram/ The tag generated the value that is inside href attribute only in case when the link had an https prefix. In all other cases it concatenated the current page url with the value inside the href attribute. How can I avoid this behaviour and make the tag show only … -
Django test cases: Not able to call execute function from GraphQL Client
i am creating test cases to validate graphql api calls using graphene-django library and while trying to execute query i am getting Client obj has no attr execute where as the dir method is showing execute method, i am very confused any help is much appreciated: here is what i have tried: from django.test import TestCase from graphene.test import Client from app.graphql.schema import schema from app.graphql.tests import constants def generate_token(user): from app.serializers import TwoFactorAuthenticationSerializer return TwoFactorAuthenticationSerializer().get_token(user).access_token class AssetGraphQLTestCase(TestCase): client = Client(schema) print("outside------------------", type(client)) print("outside------------------", dir(client)) @classmethod def setUpTestData(cls): print("Setting up test data-------------------------------") cls.client = Client(schema) cls.user = constants.TEST_USER cls.organization = constants.TEST_ORGANIZATION cls.asset_1 = constants.TEST_ASSET_1 cls.headers = { "Content-Type": "application/json", "HTTP_AUTHORIZATION":generate_token(cls.user) } print("--------------------------------",type(cls.client)) print("--------------------------------",dir(cls.client)) def test_all_asset(self): print("Testing-------------------------------------------") response_data = self.client.execute(query=constants.GRAPHQL_ASSET_QUERY, varaibles=constants.QUERY_VARIABLES, headers=self.headers) print(response_data) print(response_data['data']) self.assertEqual(response_data.status_code, 200) self.assertEqual(response_data['data'], 'Expected value')` here is the output: Setting up test data------------------------------- -------------------------------- <class 'graphene.test.Client'> -------------------------------- ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'execute', 'execute_async', 'execute_options', 'format_error', 'format_result', 'schema'] Testing------------------------------------------- E ====================================================================== ERROR: test_all_asset (app.graphql.tests.test_assets_graphql_fix.AssetGraphQLTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/graphql/tests/test_assets_graphql_fix.py", line 41, in test_all_asset response_data = self.client.execute(query=constants.GRAPHQL_ASSET_QUERY, varaibles=constants.QUERY_VARIABLES, headers=self.headers) AttributeError: 'Client' object has no … -
User creation using the microsoft MSAL lib
when I am using the MSAL lib and giving all the parameters that are required , i have created some users in the tenant and when i am trying to access the same users then there is a issue it throws a error as selected user does not exsit in the tenenat , but in acutal the user exists in that tenant please help me out this is my code <!DOCTYPE html> <html> <head> <title>Azure AD B2C Authentication</title> <script src="https://cdn.jsdelivr.net/npm/msal@1.4.4/dist/msal.min.js"></script> </head> <body> <h1>Azure AD B2C Authentication</h1> <button onclick="login()">Login</button> <button onclick="logout()">Logout</button> <script> // MSAL client configuration const msalConfig = { auth: { clientId: **** authority:********, redirectUri: '*****/', }, }; const msalClient = new Msal.UserAgentApplication(msalConfig); // Login function function login() { msalClient.loginPopup() .then(response => { // Login successful console.log('Login successful'); console.log(response); }) .catch(error => { // Login failed console.error('Login failed'); console.error(error); }); } // Logout function function logout() { msalClient.logout(); } // Handle redirect callback msalClient.handleRedirectCallback((error, response) => { if (error) { console.error('Redirect callback error'); console.error(error); } else { // Access token and user information available in the response const accessToken = response.accessToken; const user = response.account; // Use the access token for authenticated API calls or other operations console.log('Redirect callback successful'); … -
Face recognition with django
import os, sys import cv2 import numpy as np import math import face_recognition # Helper class FaceRecognition: face_locations = [] face_encodings = [] face_names = [] known_face_encodings = [] known_face_names = [] process_current_frame = True recognized=" " detected =" " def __init__(self): self.encode_faces() @staticmethod def calculate_confidence(face_distance, face_match_threshold=0.6): range = (1.0 - face_match_threshold) linear_val = (1.0 - face_distance) / (range * 2.0) if face_distance > face_match_threshold: return str(round(linear_val * 100, 2)) + '%' else: value = (linear_val + ((1.0 - linear_val) * math.pow((linear_val - 0.5) * 2, 0.2))) * 100 return str(round(value, 2)) + '%' def encode_faces(self): for image in os.listdir('/home/wissal/stage/smart_authentication_dashboard/dashboard/faces'): face_image = face_recognition.load_image_file(f"/home/wissal/stage/smart_authentication_dashboard/dashboard/faces/{image}") face_encodings = face_recognition.face_encodings(face_image) if len(face_encodings) > 0: face_encoding = face_encodings[0] self.known_face_encodings.append(face_encoding) self.known_face_names.append(image) else: print(f"No faces found in image {image}") print(self.known_face_names) def run_recognition(self): # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() # Only process every other frame of video to save time if self.process_current_frame: # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Find … -
"June 8 2023, 02:00 pm" change to "8 June 2023, 14:00"
please help me figure this out. I made a project on django on Windows OS, transferred it to debian server, everything works, but there is a problem with displaying the date: I use updated_at = models.DateTimeField(auto_now=True), on Windows OS it is displayed as: 8 June 2023, 14:00, but on debian for some reason it is displayed as: June 8 2023, 02:00 pm. What could be the problem? How to fix? -
How to remove trailing slash in the URL for API created using Django Rest Framework
I have created a django web-app and created rest apis for the same. Here is the project structure main_project | |___api | |___product this is the urls.py in the main_project. urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/", include("api.urls")) ] There is urls.py inside the api folder like this urlpatterns = [ path("product/", include("api.product.urls"))] Now inside the product folder I have created a urls.py file urlpatterns = [ path("<str:id>", ProductView.as_view(), name="product") ] Now when I run these apis on Postman I do get a trailing slash and the urls look like this localhost:8000/api/v1/product/xyz123 also when I have to query something the urls look like this localhost:8000/api/v1/product/?sorting_field_name = product_name/ Now as per the convention this is an incorrect way of naming urls, I want to remove those unnecessary trailing slashes. How do I solve this? -
Connection Error While Synchronizing Permission for Keycloak Realm in Django
When I try to synchronize permission for a realm from Keycloak in Django, I got the following error. Ayone knows the way of it? -
Why can't I use inspectdb command with terms table in Django project?
I'm trying to create a model for terms table in models.py file using inspectdb command in Django project. The terms table contains information about students and their GPA for three grades. I'm using Oracle 18 database and Django 3.2. When I try to execute this command: python3 manage.py inspectdb terms > models.py I get this message: Unable to inspect table 'terms' The error was: 'STU_ID' I don't know what is the error with STU_ID column, it exists in the database and has a valid data type and constraints. I tried to use --exclude option to exclude the column from inspection, but it didn't work. I got this message: manage.py inspectdb: error: unrecognized arguments: --exclude I also tried to use --table-filter option to inspect only terms table, but it also didn't work. I got the same message: manage.py inspectdb: error: unrecognized arguments: --table-filter I don't understand why these options are not available in Django 3.2, they are mentioned in the official documentation. Is there a solution for this problem? How can I create a model for terms table in models.py file? Thank you. -
Docker compose up -d can not see new files
I'm using docker compose to up my django app on server And for some reason if i using git pull to get new files from github command up -d can not see new files I need to use up -d --build but i dont want to build docker everytime when i update my app Thats what im using docker-compose down --remove-orphans git pull docker-compose -f docker.compose.yml up -d This is only way this works docker-compose -f docker.compose.yml up -d --build I'm using django and nginx -
script not working as expected in django_elastic_dsl,
model shop class Shop(models.Model): name = models.CharField(max_length=100) lat = models.DecimalField( null=True, blank=True, decimal_places=15, max_digits=19, default=0 ) long = models.DecimalField( null=True, blank=True, decimal_places=15, max_digits=19, default=0 ) radius = models.FloatField(default=5) address = models.CharField(max_length=100) city = models.CharField(max_length=50) @property def location_field_indexing(self): return { "lat": self.lat, "lon": self.long, } document @registry.register_document class ShopDocument(Document): location = fields.GeoPointField(attr="location_field_indexing") id = fields.TextField(attr="id") name = fields.TextField(attr="name") radius = fields.FloatField(attr="radius") class Index: name = "shops" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Meta: # parallel_indexing = True # queryset_pagination = 50exit fields = ["id", "name"] class Django: model = Shop my lookup lat = 10.943198385746596 lon = 76.66936405971812 distance = 1 shops = ( ShopDocument.search() .filter( Q( "script_score", query={"match_all": {}}, script={ "source": """ def distance = doc['location'].arcDistance(params.lat, params.lon); def radius = doc['radius'].value; def total_distance = params.dis.value + radius; if (distance <= total_distance) { return distance; } else { return 0; } """, "params": { "lat": lat, "lon": lon, "dis": { "value": distance }, }, }, ) ) .sort( { "_geo_distance": { "location": { "lat": lat, "lon": lon, }, "order": "asc", "unit": "km", "distance_type": "plane", } } ) .extra(size=10, from_=0) ) my requirement: get the shops list from the Elastic document that does not fare more than the value of the …