Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error : django.db.utils.OperationalError: (2002, "Can't connect to server on 'db' (115)"), while trying to host django-mysql on docker
So basically I am trying to setup my Django-MySQL backend on Docker but I am getting errors and not able to run the server. I went through previous answers it didn't help that's why I am putting it here again. I have tried various ways , so i'll list them out and provide the errors as well. First of all here are the required files Django settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'PASSWORD': 'pass', 'HOST': 'db', # Use 'localhost' for a local MySQL server 'PORT': '3306', # MySQL default port } } DockerFile FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /Pizza-Delivery-System WORKDIR /Pizza-Delivery-System COPY . /Pizza-Delivery-System RUN apt-get update RUN apt-get update && apt-get install -y iputils-ping RUN pip install -r requirements.txt EXPOSE 8000 docker-compose.yml version: '3' services: db: hostname: 'db' image: mysql:8.1.0 environment: MYSQL_DATABASE: db_name MYSQL_ROOT_USER: "root" MYSQL_ROOT_PASSWORD: "password" ports: - "3306:3306" volumes: - ./mysql-data:/var/lib/mysql web: build: context: . dockerfile: Dockerfile command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/Pizza-Delivery-System ports: - "8000:8000" depends_on: - db Now here is the method I have tried running all services at once docker-compose up -d In this case I got following error: manually running db service first … -
Add method to the Django CMS Page Model
Problem/Gap The Django CMS documentation clearly describes the process for extending the Page and Title Models. However, documentation on the possibility of adding a method such as the property method below is lacking, or I can't seem to find it. Note: The example provided works perfectly when I include it directly under the Django CMS Page model. This is not the preferred way of course. Question Say I want to add the below method to the Page (cms.models.pagemodel.Page) or Title Model (assuming they are likely to follow the same process) outside the CMS app. How can this be achieved? @property def my_custom_page_property(self): try: logger.info(f'Working....') return {} except Exception as e: logger.error(f'Error: {e}') return {} Attempt In a seperate app I added the code below, and migrated. The image field is properly configured and works fine. The method however doesn't seem to return anything. from cms.extensions import PageExtension from cms.extensions.extension_pool import extension_pool class MyCustomExtension(PageExtension): image = models.ForeignKey(Image, on_delete=models.SET_DEFAULT, default=None, blank=True, null=True) @property def my_custom_page_property(self): .. -
Why does one of my django model classes not return any data, when using a filter
Here is the first section of the view: class PropertyView(models.Model): idproperty = models.IntegerField(db_column='idProperty', primary_key=True, blank=False, null=False) # Field name made lowercase. address1 = models.CharField(db_column='Address1', max_length=50) # Field name made lowercase. address2 = models.CharField(db_column='Address2', max_length=50, blank=True, null=True) # Field name made lowercase. I am trying to filter on the first field, 'idproperty'. Here is the Django view: def property_detail(request, pk): prop = Propertytable.objects.get(pk=pk) propertylist = PropertyView.objects.filter(idproperty=prop.idproperty) context = { "property": propertylist, "thisprop": prop } return render(request, "property/property_detail.html", context) The 'prop' is returned correctly (from a mysql table). But the 'propertylist' returns nothing. I do not get any error. The database view, when run directly in mysql, returns the correct data. I constructed the model manually, and I wonder if I have made a mistake. In the same app, there are other views (i.e. model based on mysql views) which work fine. -
I accidentally closed my cmd and i cant re run my Django server again
when I open my cmd again it doesnt run my server and shows this error C:\Users\16478\my_tennis_club>py manage.py runserver Unable to create process using 'C:\Users\16478\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' I even tried activating my env again but it didn't work out -
Error Failed building wheel for pillow while installing on Windows
I'm trying to install Pillow on python 3.10 using command pip install Pillow and it occurs ERROR: Failed building wheel for Pillow below: (venv) PS C:\Users\Mohamad\PycharmProjects\faracode_project> pip install Pillow Collecting Pillow Using cached Pillow-10.0.1.tar.gz (50.5 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [198 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-310 creating build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying … -
Check decorator is attached to a view function
@permission_required() def my_home(request): import functools from walterwhite.views import my_nav # Replace with your view function if hasattr(my_nav, 'wrapped') and isinstance(my_nav.wrapped, functools.partial): print(f'{my_nav.name} has the @permission_required decorator') else: print(f'{my_nav.name} does not have the @permission_required decorator') return HttpResponse('In home') @permission_required() def my_nav(request): Res='Hello this is the navigation bar' return render(request,'index.html') Here it giving me the response as my_nav does not have @perm decorator even though it has decorator attached. How to check whether permission_required is attached or not -
Is there away of Reloading(Refreshing)Django Server automatically without using Ctrl +s or even Ctlrl +c and then runing it again
your text** """ I have Managed to build a web hosting platform using django i intend to make the platform free webhosting platform but the problem i have is that my django server needs to reload from time to time .i have tried the following options bellow. import time import schedule import keyboard from threading import * from datetime import datetime import django from django.utils import autoreload class ExitCommand(Exception): pass def load(): try: django.setup() keyboard.press_and_release("Ctrl+c") autoreload.autoreload_started autoreload.DJANGO_AUTORELOAD_ENV autoreload.file_changed run=autoreload.StatReloader() run.should_stop=False run.run_loop() print("Server changes detected") now=autoreload.get_reloader() now.notify_file_changed(os.path.join(BASE_DIR)) raise ExitCommand() except ExitCommand: keyboard.press_and_release("Ctrl+s") # autoreload.autoreload_started # autoreload.get_reloader() # autoreload.DJANGO_AUTORELOAD_ENV # autoreload.raise_last_exception() # autoreload.iter_all_python_module_files() # autoreload.restart_with_reloader() os.system("python manage.py runserver 8080") print("++Reloading Server+++") def relaod_server(): load_time="22:59:00" now=datetime.now() current_time=now.strftime("%H:%M:%S") start_time=datetime.strptime(load_time,"%H:%M:%S") stop_time=datetime.strptime(current_time,"%H:%M:%S") time_diffrence=start_time-stop_time os.environ["RELOAD_HOURS_REMAINING"]=str(time_diffrence) schedule.every().day.at("23:47").do(load) while True: schedule.run_pending() time.sleep(1) refresh=Thread(target=relaod_server,args=[]) refresh.setDaemon(True) refresh.start() `your text` What am trying to do is to make django server reload automatically after some time kindly help,i am working on my company start up.i am working on a webhosting paltform which i have finished writing the only challange i have is that my django server needs to reload and i dont know how to do that. -
More than one Django website on IIS server - it is possible?
I'm trying to run a Django website on an IIS server. After several tries, I finally succeeded. It works quite nicely. Now it's time for the next stage with which I have a bit of a problem. My question is: Is it possible to run more than one Django service on an IIS server? If I look at the web.config file, there are references to only one Django website. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\inetpub\wwwroot\test_3\venv\Scripts\python.exe|C:\inetpub\wwwroot\test_3\venv\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\test_3" /> <add key="WSGI_HANDLER" value="mysite.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="mysite.settings" /> </appSettings> </configuration> Especially when each website will be in a separate venv. Thanks for any help and suggestion -
How to prevent increase a field in Django
i have a model in django called products. that have a field called star that store my score of products (from 0 to 5) and i want to not allow to increase more that 5 (or even be negative number). star = models.IntegerField(default=0, max_length=5) <div class="d-flex justify-content-center small text-warning mb-2"> {% with ''|center:item.star as range %} {% for _ in range %} <div class="bi-star-fill"></div> {% endfor %} {% endwith %} </div> what can i do? for example if one of my products have star field with 7 it show 7 star in product page! -
Elasticsearch query not working with custom field
I have two models: class Teacher(models.Model): name = models.CharField(max_length=50) class TeacherSalary(models.Model) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) salary = models.IntegerField() year = models.IntegerField() I created two corresponding documents: @registry.register_document class TeacherDocument(Document): class Index: name = 'teachers' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Keyword fields = [ 'id', 'name' ] @registry.register_document class TeacherSalaryDocument(Document): name = fields.KeywordField() class Index: name = 'teacher_salary' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = TeacherSalary def prepare_name(self, instance): return instance.teacher.name When I search for some teachers by name, for example: documents = TeacherDocument.search().query('match', name="John") I have all teachers with name contains "John" for example John Thomson, Thomas John... However, when I do the same search with the TeacherSalaryDocument, I got nothing, i have to search the exact name. For example: documents = TeacherSalaryDocument.search().query('match', name="John") returns [], but documents = TeacherSalaryDocument.search().query('match', name="John Thomson") returns all salary histories of the "John Thomson" teacher. How could I get the salary of all teachers that their names contain "John"? Thank you! -
Django websockets connection failed
I have hosted a django application on Linode which includes a chatting functionality. I am using django-channels to implement that functionality. I am not using any particular technology like Redis, just the inbuilt django thing to implement the websockets because I am just testing the site for now. The following is the chatroom.html file: {% extends 'common_anime_chat/base.html' %} {% load static %} {% block stylesheet %} <link rel="stylesheet" type="text/css" href="{% static 'chatroom.css' %}"> {% endblock stylesheet %} {% block content %} <div class="chat-container"> <div id="chat-messages" style='height: 75vh;'></div> <div id="input-container"> <textarea id="input" rows="1"></textarea> <input type="button" id="submit" value="Send"> </div> </div> {{ request.user.username|json_script:"user_username" }} {{ request.user.profile.profile_picture.url|json_script:"user_pfp"}} <script> const hardcodedProfilePictures = { 'itsmyname': '/media/profile_pictures/profile1.png', 'user123': '/media/profile_picturues/profile2.png', // Add more hardcoded profile pictures here for other usernames }; document.querySelector('#submit').onclick = function (e) { const messageInputDOM = document.querySelector('#input'); const message = messageInputDOM.value; chatSocket.send(JSON.stringify({ 'message': message, 'username': userUsername, 'user_pfp':userPfp, 'room_name':roomName })); messageInputDOM.value = ''; }; const chatMessagesDOM = document.querySelector('#chat-messages'); const userUsername = JSON.parse(document.getElementById('user_username').textContent); // console.log(userUsername) const pathArray = window.location.pathname.split('/'); const roomName = pathArray[pathArray.length - 2]; // Use -1 if the room name is in the last segment let userPfp = JSON.parse(document.getElementById('user_pfp').textContent); // Object to store profile pictures associated with usernames let profilePictures = {}; const chatSocket = … -
How to save settings for each user on the site?
I have a site based on django. And it shows some graphs. Graphs have several settings. I need each user to be able to change these settings for themselves. How is this possible? And another question, is it possible for these parameters to be saved the next time for each user? -
The same code in django cannot run properly
enter image description here 上面注释的部分无法让程序运行会报错AttributeError: 'WSGIRequest' object has no attribute 'get' 而下面可以运行。是编译器的问题的,python版本是 3.8.3 ,django 版本是 4.2,pycharm是2022.3.3 (Professional Edition) 重新编写一样的代码可以运行,但是唯独第一次的那个代码无法运行。 -
Seeking General Django Deployment Advice
This is isn’t a conventional stack overflow question but was seeking help and wanted to ask a good community. I’m trying to deploy my Django app and was wondering what’s a good hosting service to do so. It’s not a large application and doesn’t even use a database at the moment (it will later). So free would be ideal. I’ve tried to follow some tutorials but it never works and I don’t know enough about deployment to debug and fix it effectively. If someone could dm me with Django deploying experience that’d be so good! My name is d.sons#3851 If not any help or advice on here would be greatly appreciated. -
celery nested task (tasks inside tasks)
I wrote 2 update_all_rss task but don't know which one is better. can someone explain it which one should I use? Info: each task is independent and doesn't need other task result. It would be greatly appreciated if you could provide me any suggestion to optimize overall performance of these tasks @shared_task(base=BaseTaskWithRetry, task_time_limit=600) def update_all_rss(): for xml_link_obj in XmlLink.objects.all().iterator(): update_single_rss.delay(xml_link_obj) vs @shared_task(base=BaseTaskWithRetry, task_time_limit=600) def update_all_rss(): xml_links = list(XmlLink.objects.all().iterator()) tasks = (update_single_rss.s(xml_link_obj) for xml_link_obj in xml_links) result_group = group(tasks) result_group() if it helps this is update_single_rss task: @shared_task(base=BaseTaskWithRetry, task_time_limit=120) def update_single_rss(xml_link_obj): channel_qs = Channel.objects.select_related('xml_link').prefetch_related("xml_link__rss_type").filter( xml_link=xml_link_obj) if channel_qs.exists(): channel = channel_qs.get() channel_parser = channel_parser_mapper(xml_link_obj.channel_parser) channel_info = channel_parser(xml_link_obj.xml_link) if channel.last_update != channel_info.get("last_update"): channel.last_update = channel_info.get("last_update") items_parser = items_parser_mapper(xml_link_obj.items_parser) items_info = items_parser(xml_link_obj.xml_link) ItemClass = item_model_mapper(xml_link_obj.rss_type.name) try: with transaction.atomic(): channel.save() items = ( ItemClass(**item, channel=channel) for item in items_info if not ItemClass.objects.filter(guid=item.get("guid")).exists() ) ItemClass.objects.bulk_create(items) except IntegrityError as e: return {"Message": str(e)} return {"Message": f"Channel {channel.title} was Updated"} return {"Message": f"Channel {channel.title} is Already Updated"} return {"Message": f"No channel for {xml_link_obj.xml_link} Exist"} -
Inner funtion gives error in Django Rest Framework
I have inner functions inside the main function with an IF statement but when the if condition is applied it gives this error (AssertionError: The request argument must be an instance of django.http.HttpRequest, not rest_framework.request.Request.) How can I solve this issue? Any help, please? views.py from .api_option23 import api_option23 from .api_option23 import api_option45 @api_view(["GET", "POST"]) def apiscanning(request, qrcode, action, curr_user): if request.method == "GET" or request.method == "POST": if action ==1: #do something elif action ==2: api_option23(parameters) elif action ==3: api_option45(parameters) -
Django: set filter manager at runtime
My Django app stores the same sets of data for multiple different chat servers. Each model has a server as a ForeignKey to track which server the data is from. In my views.py, I have a bunch of manager/model functions like this: def index(request) context = { 'most_pinged': User.objects.get_most_pinged_user(), 'top_emojis': Emojis.objects.get_top_emojis(user1), 'top_channels': Channels.objects.order_by('-messages')[:10] } etc. The problem: I want to make it so that these functions only operate on the data of ONE server at a time, and filter out all of the data from other servers. I'd have to write a bunch of filters, like so: def index(request, server_id): context = { 'most_pinged':User.objects.get_most_pinged_user(from_server=server_id), 'top_emojis': Emojis.objects.get_top_emojis(user1, from_server=server_id), 'top_channels': Channels.objects.filter(server__id=server_id).order_by('-messages') } Is there any way to make it so that instead of having to write a bunch of filters for my manager methods and such, I can just have User/Emoji/Chnanel.objects filter out all of the other server's data from the get-go? Managers can be used to filter data, but not dynamically like this (afaik). I'm willing to be flexible! -
Unable to setup webhook for Whatsapp Cloud API
I am trying to configure my django app url as a webhook in Whatsapp Cloud API to receive messages. On setting up the webhook, the whatsapp sends a request to the url with certain parameters and we have to return one of them to verify our url and then it is added as webhook. The problem is my app's url is not receiving any request from whatsapp. The app is hosted on pythonanywhere. I hit the same url from my browser and its working fine. I ran the same code on my local machine using ngrok and try to set up the url as webhook and it received the request from whatsapp. Furthermore i tried another flask url on pythonanywhere on another account and it also received the request. Hence it's not an issue with code or pythonanywhere also the url is accessable from browser. I am really confused. -
Django 4 - error unable to import ungettext from django.utils.translation
I'm getting the following error when trying to install djangocms-bootstrap4 File "C:\Users\warre\envs\ssenv\ssenv\Lib\site-packages\djangocms_bootstrap4\contrib\bootstrap4_grid\models.py", line 5, in <module> from django.utils.translation import ungettext ImportError: cannot import name 'ungettext' from 'django.utils.translation' (C:\Users\warre\envs\ssenv\ssenv\Lib\site-packages\django\utils\translation\__init__.py) -
Django: Validate DateTimeField based on another DateTimeField
I'd like to validate a DateTimeField based on another DateTimeField in the same mode, like so: class Operation(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE) start = models.DateTimeField(auto_now_add=True) end = models.DateTimeField( null=True, blank=True, validators=[ MinValueValidator(start) ] ) I get a TypeError exception when POSTing: '<' not supported between instances of 'datetime.datetime' and 'DateTimeField' These are the variables: a datetime.datetime(2023, 1, 10, 0, 25, 29, tzinfo=zoneinfo.ZoneInfo(key='America/Sao_Paulo')) b <django.db.models.fields.DateTimeField: start> self <django.core.validators.MinValueValidator object at 0x104ded4d0> I suppose I need to extract the datetime.datetime from the field, but I can't seem to do it from inside the model validator. Any tips? Thank you. -
Detecting if a site is refreshed on a mobile phone
I developed this js code, that should detect when a site is loaded for the first time or is refreshed. I send this information tho a django view. The problem is that it works on PC but not on mobile devices like phones, tablets, etc... Here is the javascript code: window.addEventListener('load', function() { // Check if the page has been reloaded var isReloaded = sessionStorage.getItem('isReloaded'); if (!isReloaded) { // It's the first visit or a new session sessionStorage.setItem('isReloaded', 'true'); // Perform actions for the first visit here } // Send the reload information to the server var isRefreshed = isReloaded ? 'true' : 'false'; var csrfToken = '{{ csrf_token }}'; $.ajax({ type: "POST", url: '', data: { 'is_refreshed': isRefreshed, 'csrfmiddlewaretoken': '{{ csrf_token }}' // Include CSRF token for security }, dataType: 'json', success: function(data) { // Handle the response from the server here, if needed console.log(data.message); }, error: function(xhr, status, error) { // Handle errors here, if needed console.error(error); } });// Replace with your CSRF token // Make an AJAX request here to send 'isRefreshed' and 'csrfToken' to the server. }); -
Django TypeError: issubclass() arg 1 must be a class when trying to create a simple tag
When trying to create a simple tag in django to reassign a variable in a django template, I am getting the error TypeError: issubclass() arg 1 must be a class. custom_templates.py: from django import template register = template.Library() @register.simple_tag def define(val=None): return val part of my settings.py: ... INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "crispy_forms", "crispy_bootstrap4", "main.apps.MainConfig", "register.apps.RegisterConfig", "main.customtemplates.custom_templates.define" ] ... I believe this is everything interacting with my simple tag, if any other information is required, please let me know. Any help is appreciated! I've tried giving the val argument in my define function a preset value, I've tried removing this, and I've tried giving type suggestions, e.g., def define(val:bool): -
Messing up the event handler in django, help me figure it out
My models: class Product(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='owner') allowed_users = models.ManyToManyField(User) def __str__(self): return self.name class Lesson(models.Model): name = models.CharField(max_length=255) link = models.URLField() time = models.PositiveIntegerField() products = models.ManyToManyField(Product) def __str__(self): return self.name class UserLessons(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) lesson = models.ForeignKey(Lesson, on_delete=models.PROTECT) is_view = models.BooleanField(default=False) view_time = models.PositiveIntegerField(default=0) date_view = models.DateField(null=True) def __str__(self): return f'{self.user.username} - {self.lesson.name} I am implementing an event handler that should create a record in the DB when creating a Lesson record @receiver(post_save, sender=Lesson) def create_user_lessons(sender, instance, **kwargs): products = instance.products.all() allowed_users = [] for product in products: for user in product.allowed_users.all(): if user not in allowed_users: allowed_users.append(user) for user in allowed_users: UserLessons.objects.create(user=user, lesson=instance) But I came across the fact that instance.products.all() outputs an empty QuerySet, although it is not empty when creating a record. What is the reason for this behavior and how to solve it? I tried to redefine the save() method, but it didn't help in any way, but an important clarification appeared, instance.products.all() gives an empty qs only for the record that was created at the moment, the rest of the records work fully, when choosing another, everything is saved as needed -
dajngo pagination for products, problem with pagination when query
I'm working on a Django project for building a website, and I'm facing an issue when filtering through a search bar by name; the pagination is not working correctly. When filtering def mart(request): query = request.GET.get('q') temperature = request.GET.get('temperature') if temperature is None: temperature = 150 products = Product.objects.all() if query: products = products.filter(Q(name__icontains=query)) for product in products: latest_log = Log.objects.filter(product_uuid=product).order_by('-date').first() if latest_log: temp = latest_log.course_temp product.temperature = temp else: product.temperature = 0 products = sorted(products, key=lambda x:x.temperature, reverse=True) paginator = Paginator(products, 20) page_number = request.GET.get('page') page_products = paginator.get_page(page_number) product_info_list = [] for product in page_products: latest_log = Log.objects.filter(product_uuid=product,course_temp__lte=temperature).order_by('-date').first() all_productbadges = Productbadge.objects.filter(product_uuid=product) badges_urls = [] if all_productbadges: for productbadge in all_productbadges: badge_id = productbadge.badge_id badge_instance = Badge.objects.filter(label=badge_id).first() if badge_instance: badge_url = badge_instance.url badges_urls.append(badge_url) if latest_log: product_info = { 'product': product, 'latest_log': latest_log, 'badges_urls': badges_urls } product_info_list.append(product_info) print("@@@@@@@@@") print(page_products.next_page_number) context = {'product_info_list': product_info_list, 'page_products': page_products} return render(request, 'courses/mart.html', context=context) paginator = Paginator(products, 20) page_number = request.GET.get('page') page_products = paginator.get_page(page_number) product_info_list = [] for product in page_products: latest_log = Log.objects.filter(product_uuid=product,course_temp__lte=temperature).order_by('-date').first() all_productbadges = Productbadge.objects.filter(product_uuid=product) badges_urls = [] if all_productbadges: for productbadge in all_productbadges: badge_id = productbadge.badge_id badge_instance = Badge.objects.filter(label=badge_id).first() if badge_instance: badge_url = badge_instance.url badges_urls.append(badge_url) if latest_log: product_info = { 'product': product, 'latest_log': … -
Django app on Google App Engine not connecting to Google Cloud SQL
I've encountered an issue when deploying my Django application on Google App Engine and trying to connect it to Google Cloud SQL. The application works perfectly on my local system, but when deployed, I get the following connection error: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? This is the code snippet for my settings.py file: DATABASES = {"default": env.db()} # If the flag as been set, configure to use proxy if os.getenv("USE_CLOUD_SQL_AUTH_PROXY", None): DATABASES["default"]["HOST"] = "127.0.0.1" DATABASES["default"]["PORT"] = 5432 # [END gaestd_py_django_database_config] # [END db_setup] # Use a in-memory sqlite3 database when testing in CI systems # TODO(glasnt) CHECK IF THIS IS REQUIRED because we're setting a val above if os.getenv("TRAMPOLINE_CI", None): DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } I have followed this guide for setting up my application on google app engine. These are all the troubleshooting steps I have tried so far - Enabled the Cloud SQL Admin API. Added Cloud SQL Admin role to the App Engine service account. Tested Connectivity from App Engine to SQL instance. Tried Restarting the Cloud SQL instance and App Engine Instance. Checked …