Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I send data to excel file/invoice from django models?
I have a Django model for different companies. When someone does not turn up for work at those companies they call our agency and we send an agent to cover that shift. They then have the manager at that company approve the digital timesheet and the values are saved in a Django model called timesheets. enter image description here My question: I want to implement payroll for over 50 users. Proposed solutions: Do I generate CSV files with the data from the model then pass the data from CSV to an excel file, or is there a better more elegant solution to this problem. PS: Please forgive my verbiage. -
Django Custom Field - Boolean -> CHAR YN
Due to a legacy system I'm trying to get Django boolean fields to save in the dB as a simple 'Y' or 'N' char field (VARCHAR not supported in said legacy system). Using a django custom field I have it working but struggling to get Django admin to work with the field. class BooleanYN(models.BooleanField): """ We need to save boolean variables as CHAR Y/N """ description = _("Boolean field stored as Y or N in the dB") def from_db_value(self, value, expression, connection): if value in ('Y', 'y'): return True if value in ('N', 'n'): return True raise ValidationError(_(f"Value in dB is not Y or N - {value}")) def get_prep_value(self, value): if value is True: return 'Y' if value is False: return 'N' return value def db_type(self, connection): return char(1) In Django admin, single record view + list view, the checkbox widget is always flagged as true even though 'N' is correctly saved in the dB and "to_python" is correctly being passed 'False' or 'True' as the value when its called by the modelform code depending on whether 'Y' or 'N' in the dB. Any help appreciated! -
Set timer for a Django view execution
I'm struggling trying to prevent a Django view from being executed more than once within an hour period. In other words, if the function runs at 15:00, all future requests should be ignored until 17:00 when it's allowed to run once again. Tried with a timer, but it does get reset every time the view is called. Maybe someone can point me in the right direction? Thanks!!! import threading as th def hello(): print("hello, world") def webhook(request): tm = th.Timer(3600, hello) if request.method == 'POST' and not tm.is_alive(): tm.start() code_to.ecexute() return HttpResponse("Webhook received!") -
Override Django Abstract Admin Model
I've the model below: class UrlsModel(TimeManager): name = models.CharField(max_length=70) url = models.URLField() def __str__(self): return self.name class Meta: abstract = True and its relative admin model: class UrlsModelAdmin(admin.ModelAdmin): list_display = ["name", "url"] There is a model that add a column to UrlsModel and now I need to add this column in list_display. How I can do this? -
How can i auto fill my field and make it non editable in django admin site
I need to autopopulate a field in admin site and make foreignkey field non editable with current_user : views.py: def my_view(request): obj = model.objects.first() response = HttpResponse(file, content_type=' application/vnd.ms-excel', ) return response urls.py: path('temo/fill',views.my_view,name = 'my-view') models.py class Model(BaseModel, SingletonModel): file = models.FileField( upload_to='', validators=[FileExtensionValidator([''])] ) person_uploaded = models.ForeignKey( 'somemodel', related_name='s', null=True, on_delete=models.SET_NULL, ) admin.py: @admin.register(tTemplate) class TemplateAdmin(admin.ModelAdmin): list_display = ('file','person_uploaded',) readonly_fields = ('person_uploaded',) def save(self, request): if not self.id: self.person_uploaded = request.user super().save() -
How to count quantity with distinct?
I have 2 templates, one representing a product sheet and the other one an actual product in stock. The stock can have several products that have the same product sheet. Example: I can have a product record "Water bottle", and several "water bottle" in the stock. My models: class Stock(models.Model): machine = models.ForeignKey( "machine.Machine", verbose_name=_("machine"), related_name="machine_stock", on_delete=models.CASCADE ) product = models.ForeignKey( "client.Product", verbose_name=_("product"), related_name="product_stock", on_delete=models.CASCADE ) epc = models.CharField(_("EPC"), max_length=80) dlc = models.DateField(_("DLC")) class Product(models.Model): name = models.CharField(_('Name'), max_length=255) [...] I want to retrieve the products in stock sorted by both DLC and name. On my frontend I want to display a table with for each row: the name of the product the dlc the number of products with this name and this dlc Example: If I have 2 product sheets (Product Model) : water bottle bottle of coca cola and I have 5 products in stock (Stock Model) : 2 bottles of water whose dlc is 02/04/2022 2 bottles of cola whose dlc is the 02/04/2022 1 bottle of cola whose dlc is 03/04/2022 I want to display 3 lines in my table: Quantity | Name | DLC 2 | water | 02/04/2022 2 | cola | 02/04/2022 1 … -
Custom Django signup/login form
I have designed signup and login forms(HTML/CSS). How can I make them work in my Django project? Should I use something like allauth and put my design on already made forms() or create my own forms and views? In books that I read author always used auth or allauth apps.There wasn't any explanation on how to implement your own custom forms. Could you help me? My Login form: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/login.css' %}"> {% block title %}<title>Login</title>{% endblock title %} </head> {% block content %} <body> <div id="card"> <div id="card-content"> <div id="card-title"> <h2>LOGIN</h2> <div class="underline-title"></div> </div> <form method="post" class="form" action="{% url 'login' %}" > {% csrf_token %} <label for="user-email" style="padding-top:13px"> &nbsp;Email </label> <input id="user-email" class="form-content" type="email" name="email" autocomplete="on" required /> <div class="form-border"></div> <label for="user-password" style="padding-top:22px">&nbsp;Password </label> <input id="user-password" class="form-content" type="password" name="password" required /> <div class="form-border"></div> <a href="#"> <legend id="forgot-pass">Forgot password?</legend> </a> <a href="{% url 'home' %}"> <input id="submit-btn" type="submit" name="submit" value="LOGIN" /> </a> <a href="#" id="signup">Don't have account yet?</a> </form> </div> </div> </body> {% endblock content %} </html> -
<HttpResponseNotFound status_code=404, "text/html"> in django-test
I'm new to unit testing and I've been trying to test a GET method of the card game that I've built. My TestCase is the following: def test_rooms(self): c = APIClient() room_id = PokerRoom.objects.get(name='planning').id request = c.get('http://127.0.0.1:8000/room/{}'.format(room_id)) print(request) The id is a UUID that's why I'm using the room_id method. My url: path('room/<int:pk>', room), where room is a @api_view(['GET']) method and pk is the id of the room. But when I try to test it, an error occurs: <HttpResponseNotFound status_code=404, "text/html"> Checked if the room exists in the test database and it exists, now I don't know what is happening. Can someone help me? -
How to pass data to Django forms from
I would like to pass my job_title from my views.py to be used to query the database in my ModelForm in forms.py. I am currently able to get the job_title from the url and pass it to my views.py. The challenge I currently have is that I keep getting errors whenever I try to query the database in my ModelMultipleChoiceField to get the particular job requirements for a specific job title. I have tried to use solutions from some articles that i found on both this site and the web. urls.py urlpatterns = [ path('application_form/<str:job_title>/', views.application_form, name='application_form'), ] views.py def application_form(request, *args, **kwargs): try: job_title = kwargs.get('job_title') get_query_data = {'job_title__job_title': job_title} model_obj = Requirements.objects.filter(**get_query_data) form = ApplicationForm(request.POST or None, model_obj) context = {'form': form} if request.method == 'GET': return render(request, 'requirements/job_specs.html', context) if request.method == 'POST': print(form.is_valid()) if form.is_valid(): form.save() return JsonResponse({'created': True}) return JsonResponse(form.errors.as_json(), safe=False) except Exception as e: print(e) form = ApplicationForm(request.POST or None) context = {'form': form} return render(request, 'requirements/job_specs.html', context) models.py class Job(models.Model): company = models.CharField(max_length=35, default='ZICTA') job_title = models.CharField(max_length=40) description = models.TextField(max_length=250) def __str__(self): return self.job_title class Requirements(models.Model): job_title = models.ForeignKey(Job, on_delete=models.CASCADE) required = models.CharField(max_length=250) def __str__(self): return self.required class Applicants(models.Model): email = models.EmailField(max_length=30) required … -
How to show the validation error in a Django form?
I am new to Django. I am trying to make a simple form to match the password. However, when I enter different passwords and press the Save button I get a cleared form instead of showing the validation error. Here newuser.html: {% block content %} <form method="POST"> {% csrf_token %} <table> {{frmNewUser.as_table}} {% for error in frmNewUser.password.errors %} {% comment %} I tried frmNewUser.non_field_errors too {% endcomment %} <p>{{error}}</p> {% endfor %} </table> <input type="submit" name="Save" value="Save" colspan=2> </form> {% endblock content %} Here forms.py: class NewUserFrom(forms.Form): username = forms.CharField(max_length=50, widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput) email = forms.EmailField(max_length=50, widget=forms.EmailInput) def clean(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return super().clean() Here views.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc from .forms import NewUserFrom def newUser(request): form = NewUserFrom(request.POST) if not form.is_valid(): return render(request,'login/newuser.html', {'frmNewUser':NewUserFrom}) return render(request, "login/welcome.html") -
Python Django s3 error "file must be encoded before hashing"
We send a file via API. When the file is saved locally or on the same ec2 instance, all works fine, and we get the response from the API When the file is saved on AWS s3, we get the error 'Unicode-objects must be encoded before hashing' This is the code that works to open and send file from local device but not when getting the file from s3 my_file = self.original_file.open(mode='rb').read() -
Make ModelMultipleChoiceField with FilteredSelectMultiple widget - read only
In my project i use an intermediary model CustomizedUserGroups to keep relations between CustomizedUser and Group models: # models.py class CustomizedUser(AbstractUser): first_name = models.CharField(max_length=255, verbose_name='имя') last_name = models.CharField(max_length=255, verbose_name='фамилия') # other fields groups = models.ManyToManyField(Group, verbose_name='группы', related_name='users', through='CustomizedUserGroups') Therefore in admin class (CustomizedUserAdmin) for CustomizedUser i can't let fieldsets contain 'groups' (otherwise The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. will happen). So, i defined fieldsets manually (with no groups) and problem was solved. # admin.py class UserAdminCustomized(FilterByMedicalCenterMixin, BasicModelAdmin, UserAdmin): fieldsets = ((None, {'fields': ('username',)}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'patronymic', 'role', 'email')})) It is intended, that value for groups field in model CustomizedUser is assigned automatically depending on other values from registration form fields, therefore when a user adds a new user via admin panel, there is no need to display groups field. But when a user wants to edit other user's data via admin panel, i want the group field to be shown to him in read only mode. To solve this i created ExtendedUserChangeForm, where i defined a group_list field: # forms.py class ExtendedUserChangeForm(UserChangeForm): group_list = forms.ModelMultipleChoiceField(label='Группы пользователя', queryset=Group.objects.all(), required=False, widget=FilteredSelectMultiple('группы пользователя', False, attrs={ 'disabled': True })) I … -
Perform update on Django Rest Framework
ive got a class that adds a number of points in an instance, but i want to limit it, so that only one user can upvote one answer. One user can't do it twice, but other users can also upvote it only once: class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) def perform_update(self, serializer): if not serializer.addition_done and self.request.user not in serializer.voters.all(): serializer.number_of_points += 1 serializer.addition_done = True serializer.save() class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) addition_done = models.BooleanField(default=False) subtraction_done = models.BooleanField(default=False) voters = models.ManyToManyField('users.CustomUser', default=None, blank=True, related_name='voters') class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points', 'addition_done') But i get an error like this AttributeError: 'AddPointsSerializer' object has no attribute 'addition_done' Do you have any idea why? -
Django, how to add a watermark of primary key on the image that is submitted with the form?
I have a form that takes some values from the dropdowns and an image as well(optional) and then submits the data to the database. The primary key of form is the collective values of all the options selected separated by "_" e.g. if someone selects A from first dropdown, 33 from second dropdown, football from third dropdown, the form would be submitted with primary key "A_33_football" and it would be unique for this form only. I want when image is submitted along with this form, it should have this primary key watermarked on it. Is there a way doing this Django? -
how pass an id into an api with django
hi i am new to working with api, i am trying to pass an id into the api this way, but it returns a none value from django.shortcuts import render import requests import json def hacker_news(request): response = requests.get( 'https://hackernews.firebaseio.com/v0/topstories.json') topstories = response.json() item_id = topstories[0] print(item_id) url = ('https://hacker-news.firebaseio.com/v0/item/{item_id}.json') re = requests.get(url) story = re.json() return render(request,'comment.html', {'story':story}) -
Filter queryset by subquery on two conditions
I need to filter SomeModel queryset on max date by groups (user field). The Model looks like: class SomeModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=date.today) ... I've already created some kind of subquery: from django.db.models import Max subquery = (SomeModel.objects .all() .values('user') .annotate(latest_date=Max('date'))) So I want to use this subquery to filter SomeModel queryset on two conditions: # pseudocode SomeModel.objects.filter(user==subquery.user and time==subquery.latest_time) Is it possible at all or my approach is wrong? -
NGINX no live upstreams while connecting to upstream
I have Django app, running in Docker container on a host. Also on a host I have Nginx server for this app. Problem that like every 5 - 10 days server not respond and I must restart app container, I don't know what can be wrong. My Nginx conf: upstream django_service { server 127.0.0.1:8001 max_fails=0 fail_timeout=10; } server { listen 443 ssl; listen [::]:443 ssl; server_name domain.com; charset utf-8; client_max_body_size 16M; ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot # include /etc/letsencrypt/options-ssl-nginx.conf; if ($scheme != "https") { return 301 https://$host$request_uri; } location /media { alias /home/paket/paket2x/var/www/media; } location /static { autoindex on; alias /home/paket/paket2x/var/www/static; } location / { proxy_read_timeout 600; proxy_pass http://django_service; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect http://localhost:8001 https://$server_name; access_log /var/log/nginx/paket.access.log paketlog; error_log /var/log/nginx/paket.error.log; } } server { listen 80 default_server; listen [::]:80 default_server; server_name domain.com; return 301 https domain.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot server_name www.domain.com; # managed by Certbot return 301 https domain.com$request_uri; } server … -
How to convert Django project into mobile app
I am new in Django. I need some help to convert Django website into mobile app. Please tell someone what to do. am not able to convert it. please tell me. This help will be good for me as a fresher. I don't have any knowledge about converting Django project into mobile app. Please tell some guide to do that. please -
Django Rest Framework testing with python queue
I have a simple DRF application with a Python native queue that I'm currently writing tests for. One of the API's accepts a file, which is then put in a python queue for processing. This works fine in the Django app. However, I can't figure out how to test this properly. When I call the the API with a Django API Client, I see that the file is put in the queue, and processing is started. However, as the response is returned, the tests finishes before the task of the queue is done. This task is then never completed. I also cannot make the test sleep, cause this seems to pause the queue as well. Which is strange, cause they should be on different threads. Additionally, the default tearDown results in a ObjectInUse error from psycopg2 as the test db is in use. I presume this is my queue accessing the DB, so how can I close my queue properly so that the teardown doesn't err? My test: from django.test import TestCase from rest_framework.test import APIClient class UploadTestCase(TestCase): def setUp(self): self.client = APIClient() self.client.force_authenticate() def test_post_file(self): with open('tmp.csv', 'rt') as f: response = self.client.post('/upload', data={'files': [f]}) # Asserts ... -
How to make a LEFT JOIN in django, I can't figure it out
My first model: class HdAlerts(models.Model): raised_at = models.DateTimeField(null=False) msg = models.TextField() site = models.ForeignKey( Sites, on_delete=models.CASCADE, ) alert_class = models.CharField(max_length=120) priority = models.IntegerField(null=True) severity = models.SmallIntegerField(null=True) partner = models.ForeignKey( Partners, on_delete=models.CASCADE, ) alert_id = models.TextField(primary_key=True) updated_at = models.DateTimeField(null=True) resolved_at = models.DateTimeField(null=True) ignore_until = models.DateTimeField(null=True) class Meta: managed = False db_table = 'hd_alerts' def __str__(self): return f'<ID: {self.alert_id}: [Msg: {self.msg[:10]}]>' Second: class Partners(models.Model): partner_id = models.IntegerField(primary_key=True) partner_name = models.CharField(max_length=500, null=False) is_profiles_shared = models.BooleanField(null=False) is_deleted = models.BooleanField(null=True) class Meta: managed = False db_table = 'partners' def __str__(self): return f'<Partner_ID: {self.partner_id}: [Name: {self.partner_name}]>' And last one: class Sites(models.Model): site_id = models.IntegerField(primary_key=True) site_name = models.CharField(max_length=500, blank=True) is_deleted = models.BooleanField() is_auto = models.BooleanField() partner_id = models.IntegerField(blank=True, null=True) source_id = models.IntegerField(blank=True, null=True) category_id = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'sites' verbose_name = 'Site' verbose_name_plural = 'Sites' def __str__(self): return f'Site id: {self.site_id}, Site name: {self.site_name}' I need to make the following query: SELECT p.partner_name DBA, s.site_name Site, ha.msg Messege, ha.ignore_until Ignored FROM hd_alerts ha LEFT JOIN partners p ON ha.partner_id = p.partner_id LEFT JOIN sites s ON s.site_id = ha.site_id WHERE ha.resolved_at IS NULL I don't understand how this can be done with django. I tried to pass it to raw(), but … -
Can web components UI use dynamic data from our backends DB as input?
I'm considering learning web components, either stencil or lit elements. A deal breaking for me is being able to create UI elements that can actually take data from our DB as an input and then morph the output of the UI element getting displayed. So if I have a Django backend with PostgreSQL and store two columns for [stockprice] & [timedate]. Is there a web component framework that lets me write a UI widget like this (pseudo code)... Example 1 UI - line chart stock widget CSS = rectangle(purple) var1 let [stockprice] = Y axis var2 let [datetime] = X axis CSS = 3 buttons (user options) button 1 if [datetime] >= 7days, delete (exclude) button 2 if [datetime] >= 30days, delete (exclude) button 3 if [datetime] >= 365days, delete (exclude) plot_line_chart(stockprice, datetiime) addbuttons() Example1 output. Combine UI elements into ONE widget (purple rectangle) This would in theory output a line chart with stock prices against a certain timeframe and allow the users to display if they want to view price in last 7, 30 or 365days depending on which option they click. In example 1, both the stock chart and button selection are ONE element part of the same … -
Is the sqlite database (the default django database) good enough?
I am building this ecommerce app with django, and I was thinking if the default database (sqlite) was fine enough? My django app is going to have around 200 different products, and for payments I will use stripe API. I do not expect too much traffic when the app is up, since it's a website only for the country I live in with 6 million inhabitants. So can I settle with the sqlite database? -
How to resolve this "Invalid default value for a django.models field error"?
I am creating a student model which records homework details of a student. It works in a way that student has been given work to do at home with some deadlines of days or hours. When I migrate, I get this error I am getting this error File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1067, "Invalid default value for 'deadline_type'") for my this model class WorkHour(models.Model): DAYS= 'D' HOURS= 'H' STATUS = [ ('D', 'Days'), ('H', 'Hours') ] student= models.ForeignKey(Student, on_delete=models.CASCADE) date= models.DateField(verbose_name='Date') deadline_type= models.CharField(max_length=256,choices=STATUS,default= DAYS, verbose_name= "Days/Hours") deadline_time = models.IntegerField(verbose_name='Deadline',default=1) either I add default value in deadline_type, It gives me the above error. I have done the same thing in my other models too. I din;t know what I am doing wrong here. -
Print users' data inside a template in Django
I'm new to Django and I'm trying to print users' information such as email, first name, username in a template that should work as "My Profile Page". For some reason, the only thing I'm able to print is the username of the logged-in user with {{request.user.username}} Users are registered using the UserCreationForm If I try to print the email with {{request.user.email}} or {{user.email}} nothing is shown. My settings.py is the default one TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , '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', ], }, }, ] -
Hey everyone I have problem in sorting queryset in Django
So, I am learning Django and trying to make a site similar to AirBNB. I have models called lisitngs that has latitude and longitude stored in CharField. My model is as follows: class Listing(models.Model): class BathRoomType(models.TextChoices): ATTACHED = 'Attached Bathroom' COMMON = 'Shared Bathroom' class RoomVentType(models.TextChoices): AC = 'Air Conditioner' NO_AC = 'No Air Conditioner' class LisitngType(models.TextChoices): ROOM = 'Room' APARTEMENT = 'Apartement' HOUSE = 'Full House' user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) city = models.ForeignKey(RoomLocation, on_delete=models.CASCADE) exact_address = models.CharField(max_length=255) lat = models.CharField(max_length=300, blank=False, null=False, default="0") lng = models.CharField(max_length=300, blank=False, null=False, default="0") description = models.TextField() price = models.IntegerField() listing_type = models.CharField(max_length=20, choices=LisitngType.choices, default=LisitngType.ROOM) kitchen_available = models.BooleanField(default=False) kitchen_description = models.TextField(null=True, blank=True) bedrooms = models.IntegerField() max_acomodation = models.IntegerField() bathroom_type = models.CharField(max_length=20, choices=BathRoomType.choices, default=BathRoomType.ATTACHED) no_bathrooms = models.IntegerField() room_type = models.CharField(max_length=30, choices=RoomVentType.choices, default=RoomVentType.AC) main_photo = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_1 = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_2 = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_3 = models.ImageField(upload_to='room_images', default='default_room.jpg') is_published = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now, editable=False) slug = AutoSlugField(populate_from=['title', 'listing_type', 'bathroom_type', 'room_type']) rating = models.IntegerField(default=5) approved = models.BooleanField(default=False) total_bookings = models.IntegerField(default=0) def __str__(self): return self.title In my homepage what I want to do is show the listings which are nearby me. For that I have a function named as near_places. This near_place function …