Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OR operator in Django filter creates duplicates
when I print Brand.objects.filter(Q(name__icontains=keyword)|Q(tag__name__icontains=keyword)), it yields two objects as opposed to my expectation. It should be only one. My models.py is like class Brand(models.Model): name = models.CharField(max_length=20) tag = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): name = models.CharField(max_length=20) When I print Brand.objects.filter(name__icontains=keyword) and Brand.objects.filter(tag__name__icontains=keyword) seperately, each one yields only one same object. But when I merge these two queries, it yields duplicates. I found out .distinct() solves this problem but I wanna know why. Looking forward to help! -
Reset field in Django Admin page
Imagine, that I have model and in the Django admin form I can update my fields. I want to implement something like: update one field and the second one will be reset in admin form in real time (I'll hope it can help real admin in the future do not forget redefine this second field, because it's very important in my situation). Is that possible to implement something like that without custom admin form? -
AttributeError: 'NoneType' object has no attribute 'build_absolute_uri' Django Rest Framework
I've got this Serializer translating path to url, and it works on its own, but when i try to nest this serializer inside another serializer, i get this error. Do you have any idea why? I need to have this function, because otherwise it just shows the paths to the image in this main SpecialistSerializer. class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_file_abs_url') class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) def get_file_abs_url(self, obj): request = self.context.get('request') return request.build_absolute_uri(obj.image.url) class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") class Meta: model = Entity fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) data['photos'] = EntityPhotosSerializer(many=True, instance=instance.entityphoto_set.all()).data return data Traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 282, in get return self.retrieve(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 56, in retrieve return … -
How can i deploy my django projects on heroku?
I tried to deploy my simple django project on heroku, but i couldn't understand how to solve this problem This is the git push heroku master remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.8/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input remote: ) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 898dd95ff261fc77ac4dcd00edd162d7b7c054f2 remote: ! remote: ! We have detected that you have triggered a build from source code with version 898dd95ff261fc77ac4dcd00edd162d7b7c054f2 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This … -
Invalid block tag on line 24: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag?
I'm a new in Django and trying to do a app but now I'm having this error: "Invalid block tag on line 24: 'form.as_p', expected 'endblock'." TEMPLATE {% extends "base.html" %} {% block title %} <title>Tarefas</title> {% endblock title %} {% block content %} <div class="content"> {% if messages %} <div class="container"> <br> {% for message in messages %} <div class="alert alert-info" role="alert"> {{message}} </div> {% endfor %} </div> {% endif %} <div class="container tasks-box"> <table class="table table-striped"> <form method='POST'> {% csrf_token %} {% form.as_p %} <button type="submit" class="btn btn-secondary btn-sec">Adicionar</button> </form> [...] forms.py from django.forms import ModelForm from todolist.models import Tasks class TaskForm(ModelForm): class Meta: model = Tasks fields = ['task','responsible'] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from todolist.models import Tasks from todolist.forms import TaskForm from django.contrib import messages from django.contrib.auth.decorators import login_required @login_required def todolist(request): if request.method == 'POST': form = TaskForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.manager = request.user instance.save() messages.success(request,("Tarefa adicionada")) return redirect('todolist') else: form = TaskForm all_tasks = Tasks.objects.filter(manager=request.user) all_users = Tasks.objects.all() return render(request,'todolist.html',{ 'form':form, 'all_tasks':all_tasks, 'all_users':all_users}) models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class … -
How do you start this project?
When I use the code django-admin.exe startproject mysite it gives me a blank. I don't know whats happening. Does anyone know the answer to this? -
How can i solve Foreign key mismatch error in django?
I am trying to connect the two tables in django but i am getting the error django.db.utils.OperationalError: foreign key mismatch - "website_doctor" referencing "website_field" please suggest a way to solve it -
Django - How to only allow staff users to see their own posts in admin panel
I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings here is my listings/admin.py from django.contrib import admin from .models import Listing class ListingAdmin(admin.ModelAdmin): list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date') list_display_links = ('id','Full_Name') list_editable = ('Is_Published',) search_fields = ('Full_Name','Town_Or_City','District','Region',) admin.site.register(Listing, ListingAdmin) here is my listings/models.py from django.db import models from datetime import datetime from FuneralHomes.models import FuneralHome class Listing(models.Model): index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True) Full_Name = models.CharField(max_length=200) First_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=200) Nee = models.CharField(max_length=200, blank=True) Town_Or_City = models.CharField(max_length=200) District = models.CharField(max_length=200, blank=True) Region = models.CharField(max_length=200) List_Date = models.DateField(max_length=200) Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) Is_Published = models.BooleanField(default=True) List_Date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.Full_Name -
How to test if an instance of a django model was created?
I am testing an api for a game and have some issues with a model. This is my model: models.py class Gamesession(models.Model): gamemode = models.ForeignKey(Gamemode, on_delete=models.CASCADE, null=True) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gametype = models.ForeignKey(Gametype, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) objects = models.Manager() This is the test suite: test_models.py def setUp(self): self.user = CustomUser.objects.create(id=1, username="carina") self.gametype = Gametype.objects.create(id=1, name="NewGame", rounds=5, round_duration=60, enabled=True) self.gamesession_user = self.user self.gamesession_gametype = self.gametype self.gamesession_created = datetime.utcnow().replace(tzinfo=pytz.UTC) self.gamesession = Gamesession.objects.create(id=1, user=self.gamesession_user, gametype=self.gamesession_gametype, created=self.gamesession_created) def test_create_gamesession(self): gamesession = Gamesession.objects.create(gametype=self.gametype) assert gamesession.gametype == self.gamesession_gametype Running my tests keeps retrieving the error: GamesessionTests::test_create_gamesession - django.db.utils.IntegrityError: null value in column "created" of relation "frontend_games How can I solve this? Is there a better way to test if an instance of the model is created? -
Add more fields to auth User model and then use it for authentication in Django
I want to add more fields to auth User model and then use it for registration,login and logout . For example i need an image field to store profile picture and an interger/date field to store date of birth . I having hard time understanding the custom authentication . I want to register normal user using html template and then login . -
Where to find a single understandable instructions for the method of ModelAdmin in Django
A question from a silly noob about Django I read a tutorial that described the ModelAdmin method changelist_view It looks next: class SaleSummaryAdmin(ModelAdmin): # ... def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'total': Count('id'), 'total_sales': Sum('price'), } response.context_data['summary'] = list( qs .values('sale__category__name') .annotate(**metrics) .order_by('-total_sales') ) return response This is different from what is in the documentation. Additionally, in other tutorials I have seen other versions of writing this method, like this: def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} gradeScalesSettings = gradeScalesSetting.objects.all() configurations = configuration.objects.all() rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct() extra_context.update({ "rounding": rounding, "gradeScalesSetting": gradeScalesSettings, "configurations": configurations, }) return super().changelist_view(request, extra_context=extra_context) How does it work? I don't understand how correctly to use this method, because I can't find a single instruction. I probably just don't understand the principle by which it works. Tell me in which direction I should look -
How to execute Nested loop in Django Template on single Queryset
I want to render my query set data on template with a slider. Each slider will contain 3 product query like this But I am unable to to this dynamically with for loop in Django template language. My Template code is <h4>Latest Products</h4> <div class="latest-product__slider owl-carousel"> {% for product in recent_products %} <div class="latest-prdouct__slider__item"> <a href="#" class="latest-product__item"> <div class="latest-product__item__pic"> <img src="{{product.images.url}}" alt=""> </div> <div class="latest-product__item__text"> <h6>{{product.name}}</h6> <span>{{product.price}} Tk</span> </div> </a> </div> {% endfor %} </div> here is my view function: def index(request): products = Product.objects.all() categorys = ProductCategory.objects.all() today = timezone.now().date() last_day = today - timezone.timedelta(days=7) today = datetime.strftime(today, "%Y-%m-%d") last_day = datetime.strftime(last_day, "%Y-%m-%d") print(last_day) recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time") context = { 'products': products, 'categorys': categorys, 'recent_products': recent_products } return render(request, 'index.html', context) and my model class is: class ProductCategory(models.Model): name = models.CharField(max_length=100) image = models.ImageField(blank=True, null=True) added_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField(blank=True, null=True) ratings = models.FloatField(blank=True, null=True) number_of_ratings = models.IntegerField(blank=True, null=True) images = models.ImageField(blank=True, null=True) description = models.TextField(blank=True, null=True) # user_review need to be added discount_rate = models.IntegerField(default=0) available_stock = models.IntegerField(default=0) added_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True) @property def discount(self): if … -
How do I reverse the sign in a django database query on matching rows?
I have a Django model that looks like this: direction_choices = ( ("up", "Up"), ("down", "Down"), ("left", "Left"), ("right", "Right"), ) class Movement: direction = models.CharField(max_length=5, choices=direction_choices) distance = models.PositiveSmallIntegerField() Lets say the data in my database looks like this: Movement(direction="up", 4) Movement(direction="up", 6) Movement(direction="down", 3) Movement(direction="down", 1) Movement(direction="left", 7) Movement(direction="right", 4) Movement(direction="left", 1) Movement(direction="right", 8) I want to do a database query that will calculate the total distance moved in the Y axis. In our example, it would be: 4+6-3-1 = 6 I can do something like: Movement.objects.all().filter( direction__in=("up", "down") ).aggregate( total=Sum('distance') ) which gives me: {'total': 16} I'm not sure how to tell the database that "down" fields should be multiplied by -1 to have their signs reversed before adding up the total. I know this is easy to do with Python with a for loop, or list comprehension. How would one have the database do this? -
Is there a way of using FPDF to generate a PDF file from forms in Django?
I am trying to generate a PDF file and give it a custom name using Django 4.0.2 I have 2 inputs, one for the name and one for the photos, I want to be able to generate the PDF without saving it in my database. I am using no models for this, plain html and python. I have the inputs: <input type="text" id="inputPassword6" class="form-control" aria-describedby="passwordHelpInline" name="name" /> <input class="form-control" type="file" id="formFileMultiple" multiple accept=".png, .jpeg, .jpg" name="photos" /> <div class="d-grid gap-2 mt-3"> <button class="btn btn-success" type="submit">Save PDF</button> </div> And I am trying to merge and return the PDF file like this: if request.method == "POST" or "FILES": name = request.POST["name"] photos = request.FILES["photos"] # Convert photos to PDF pdf = FPDF() # imagelist is the list with all image filenames for image in photos: pdf.add_page() pdf.image(image, 0,0,210,297) pdf.output(f"{name} AIA 114.pdf", "F") Current error: Exception Type: TypeError Exception Value: argument should be integer or bytes-like object, not 'str' It looks like FPDF can not look into the image I provided. I tried to decode the image, but I hit another error: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Can someone help me solve this problem or propose … -
AttributeError: 'Model' object has no attribute '....' Django Rest Framework
I have this model class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user') entity = models.ForeignKey('Entity', on_delete=models.CASCADE) image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) class Entity(models.Model): .... class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_img') def get_img(self, entity_photo): if not entity_photo.image: raise NotFound request = self.context.get('request') return request.build_absolute_uri(entity_photo.image.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") class Meta: model = Entity fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) data['photos'] = EntityPhotosSerializer(many=True, instance=instance.image_set.all()).data return data and after making get request I get an error: AttributeError: 'Entity' object has no attribute 'image_set' Which is weird because a few days ago i did the same thing with a model that was connected via reverse relationship the same way, i even copied the code and it worked. Do you think it might be because of the image file? I wanna show the list of Photos(that the serializer changed to url) for every Entity Instance. -
Barcodes are not scannable after html-to-pdf conversion (using weasyprint package)
I am using weasyprint package for html to pdf conversion with Django. my problem is that i can't scan barcodes in the pdf printed. !!! the only scannable format is ean13 but it can't cover my need because it can encode only 8, 12, 13, 15, and 18 digits of numbers! I used code128, code39 of libre barrcode google fonts links but i had the same problem Please, if there is somone here who did this task and it worked for him, heeelp me -
Input a CSV file from HTML and parse it to database using Django
I have a CSV file with some data, I want to create a web-page that takes the CSV file and converts it into table using django. I'm new to django and I don't know whether it is possible to automate everything... Any suggestions to approach this problem or even solutions Thank you -
500 Server Error after saving the data in django admin
My website is deployed on apache server. When I am adding image field in model. I am trying to save the object in Django admin but it is showing server error 500. But if I am removing image field in model. It is not showing any error. What should I do. -
how to set default selected value in ModelChoiceField while working with ModelForm?
I am creating a simple form through ModelForm,i have made 4 tables which consists of one main table, and 3 sub tables which is the foreign keys of main tables,everything is working perfect. But I want that there must be selected value in form which will show in the frontend by default. by default it is showing -------- in select tag of html but i want that it will show some label like in my case: it will be better if it shows Select Job Description by default rather than ------ so how can i implement that? My forms.py from django import forms from django.utils.translation import gettext_lazy as _ from numpy import empty from .models import SignUpModel class SignUpForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'First Name'}), required=True, error_messages={'required': 'First Name is required'}) last_name = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Last Name'}), required=True, error_messages={'required': 'Last Name is required'}) email = forms.EmailField(widget=forms.EmailInput( attrs={'placeholder': 'Email Address'}), required=True, error_messages={'required': 'Email Address is required'}) class Meta: model = SignUpModel fields = ['first_name', 'last_name', 'email', 'password', 'company_name', 'job', 'mobile_no', 'country', 'state'] widgets = { 'password': forms.PasswordInput(attrs={'placeholder': 'Password'}), 'company_name': forms.TextInput(attrs={'placeholder': 'Company Name'}), 'mobile_no': forms.NumberInput(attrs={'placeholder': 'Mobile Number'}), } error_messages = { 'password': { 'required': _('password is required') }, 'mobile_no': { 'required': _('Mobile … -
develope online questionnaire web app with Django
I have a Django website already and I want to upload several questionnaires to my clients can answer online. so that I can receive and interpret the answers in Django admin dashboard. Each questionnaire has several questions and the answer to each question can be multiple choice or descriptive. I created the table of Question in model.py and the questions will be write on the website through the Django admin dashboard. Now I have trouble with UserAnswer class in models.py and the UserAnswerForm in forms.py, and I also had trouble with the views and Html codes. when I submit a questionnaire no item save in Django admin dashboard. models.py: import os from django.db import models from django.contrib.auth.models import User def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): name, ext = get_filename_ext(filename) final_name = f"{instance.id}-{instance.title}{ext}" return f"image/{final_name}" # Create your models here. class AssessmentsManager(models.Manager): def get_by_id(self, assessment_id): qs = self.get_queryset().filter(id=assessment_id) if qs.count() == 1: return qs.first() else: return None class Assessments(models.Model): title = models.CharField(max_length=200, null=True, verbose_name='عنوان پرسشنامه') description = models.TextField(max_length=2500, null=True, blank=True, verbose_name='توضیحات') image = models.ImageField(upload_to=upload_image_path, null=True, blank=True, verbose_name='تصویر پرسشنامه') objects = AssessmentsManager() class Meta: verbose_name = 'ایجاد پرسشنامه' verbose_name_plural = 'ایجاد پرسشنامه ها' … -
Django ckeditor codesnippet plugin shows codes without color
I am using ckeditor in my django project, everything is working fine, but when add code snippet there is only simple text code without colors but in my admin panel it is normal. -
How do you change the title of a pdf using django?
So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason urls.py urlpatterns = [ path("show_file/r'^(?P<file_id>\d+)",v.show_file, name="show_file" ), ] views.py def show_file(response,file_id): doc = Document.objects.get(id=file_id) pdf = open(f"media/{doc.file}", 'rb') return FileResponse(pdf, content_type='application/pdf') -
Django Rest Framework 'can't set attribute' in APIView
I have an endpoint, CompanyDefaultView class that inherits APIView and AURPostCompIdMixin classes. using this endpoint i get AttributeError: can't set attribute error. this is all code in one file import logging from abc import ABC from rest_framework import status, serializers from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView logger = logging.getLogger(__name__) HEADER_USER_STATUS = 'User-Status' USER_STATUS_NOT_EXIST = 'not-exist' USER_STATUS_EXIST = 'exist' USER_STATUS_EXIST_NOT_ACTIVE = 'not-active' USER_STATUS_EXIST_ACTIVE = 'active' class RspPropsMixin: _response = None @property def response(self): return self._response _stat_code = None _rsp_headers = {} @property def stat_code(self): return self._stat_code @property def rsp_headers(self): return self._rsp_headers def _set_rsp_props(self, response, header_key, header, stat_code): self._response = response if header is not None: self._rsp_headers[header_key] = header self._stat_code = stat_code def set_rsp(self, response=None, header_key=HEADER_USER_STATUS, header=None, stat_code=status.HTTP_200_OK): self._set_rsp_props(response, header_key, header, stat_code) def set_rsp_msg(self, msg, desc=None, header_key=HEADER_USER_STATUS, header=None, stat_code=status.HTTP_200_OK): response = {'msg': msg} if desc is not None: response['desc'] = desc self._set_rsp_props(response, header_key, header, stat_code) def add_header(self, header_key=HEADER_USER_STATUS, *, header): self._rsp_headers[header_key] = header class AURMixin(RspPropsMixin): """ AuthenticatedUserRequestMixin class """ permission_classes = (IsAuthenticated,) _comp_id = None _ruser = None @property def comp_id(self): return self._comp_id @property def ruser(self): return self._ruser def handle_valid_request(self, request, http_method_data, *args, **kwargs): raise NotImplementedError("You must implement handle_valid_request method!") def handle_request(self, request, http_method_data, *args, **kwargs): … -
How to execute a method within a class without calling it, with self parameter
I am trying to make a randomized urls and save them in a database but this code keep return this error TypeError: randomizer() missing 1 required positional argument: 'self' I Tried to call The randomizer as randomizer() instead of randomizer but this does not work because it will generate random characters for once. It is the same when with qr_generator function it requires the self argument. class Table(models.Model): def randomizer(self): qr = str(self.restaurant.id).join((random.choice(string.ascii_letters) for x in range(5))) return qr def qr_generator(self): url = DOMAIN +"/table/" + self.qr qr_img = qrcode.make(url) qr_img.save(f"qrs/{self.restaurant.id}/{self.qr}.png") return f"qrs/{self.restaurant.id}/{self.qr}" number = models.IntegerField() restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) qr = models.CharField(max_length=50, default=randomizer, unique=True) qr_img = models.CharField(default=qr_generator, max_length=100) -
How to fetch specific location inside map part?
Example maps image Suppose, I've draw-line for store delivery area. Now, any user to inside draw-line delivery area then got store instance else not found object. So, How can I set django filter query for fetching the store base on user current location? from django.contrib.gis.db import models class Store(models.Model): store_name = models.CharField(default="", max_length=255, null=True, blank=True) delivery_area = models.MultiPointField(srid=4326, null=True, blank=True) Base on Above, model to I've set delivery area for store. Now, user side getting current location like, PointField(28.632194789684196, 77.2200644600461) and this location getting from user mobile. According to this location coordinate how can fetch the store.? Store.objects.filter(delivery_area=PointField(28.632194789684196, 77.2200644600461)) Like, fetch the store on above queryset.