Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fallback or Error Handling for Secondary Django Database
I have a second database in my Django application. However, I need a VPN to connect to it. If my VPN is not enabled psycop2 will throw an operational error back at me. However, I would like the ability for that database to fail silently and fallback to the default database in case the connection is refused. Is there a way to do this? I cant seem to find a default way and it seems like a very basic functionality to have. I have tried to implement something through routers suggested in stackoverflow before, but at startup my application will simply say OperationalError: Connection Refused and then crash the rest of the startup procedure. class OVIRouter: """ A router that takes all of the reads, writes and changes to the OVIDevice model (also known as "ovidevice" once the model is translated to SQL), and sends them to the OVI database (The database configured in settings.py through the "ovi_db" entry in the DATABASES constant). """ db_name = 'ovi_db' def db_for_read(self, model: Model, **hints: Any) -> Optional[str]: """ Attempts to read the OVIDevice model go to the OVI device database. If the connection to the OVI device database fails, the default database … -
Unable to add an image in Django Admin page hosted on EC2 with Apache2 server
I am learning Django deployment on EC2 with Apache server. I am able to serve static files. But when I try to add an image via Admin page, I am getting below error. The permissions for media_root is as below I am able to add image with Django server inside the instance, but with Apache server I am getting error. Apache2 is configured as below Alias /static/ /home/ubuntu/testing/dummy/static_root/ Alias /media/ /home/ubuntu/testing/dummy/media_root/ <Directory /home/ubuntu/testing/dummy/static_root> Require all granted </Directory> <Directory /home/ubuntu/testing/dummy/media_root> Require all granted </Directory> WSGIScriptAlias / /home/ubuntu/testing/dummy/dummywebsite/wsgi.py <Directory /home/ubuntu/testing/dummy/dummywebsite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess loserprocess python-home=/home/ubuntu/testing/testingenv python-path=/home/ubuntu/testing/dummy:/home/ubuntu/testing/testingenv/lib/python3.10/site-packages/ WSGIProcessGroup loserprocess WSGIApplicationGroup %{GLOBAL} I have given the permission as mentioned here, but still I am facing issue. Can you please let me know what I am missing here. Thanks -
POST 403 Forbidden Django Vue Js
I am using Vue JS and Django Rest Framework and I am trying to add a feature to add a blog post. I am not sure why I am getting a 403 forbidden error in the console. I am getting the following error: Forbidden (Origin checking failed - http://localhost:8080 does not match any trusted origins.) Any direction would be appreciated I am not sure if this is a CORS related error but I have CORS_ALLOWED_ORIGINS = ['http://localhost:8080'] in my settings.py. I have also enabled the middleware. I have a login page that works and assigns the user a token when logged in (I am using djoser). I have made sure that the user has permissions to add a blog entry. here is my code for submitform if relevant: submitForm() { const postData = { title: this.title, author: this.author, body: this.body, }; const token = localStorage.getItem('token'); // Retrieve the authentication token from local storage axios.post('/api/v1/posts/add-post/', postData, { headers: { Authorization: `Token ${token}`, // Include the token in the request headers }, }) .then(response => { console.log(response.data); // Handle success, e.g., show a success message or navigate to another page }) .catch(error => { console.log(error); // Handle error, e.g., show an error … -
Error on testcase after update from django 2 to 4
I'm updating my entire project from Django 2.2 to Django 4.2.3. I have already read the entire deprecation timeline and done regression tests, and everything is working. But, using the TestCase, I found a difference: tear_down isn't flushing the database after each test, and when it runs, models that are created in migrations are removed as well. Does anyone know what has changed between those versions that can affect tests, teardown, and flush? I tried debbug testcase source code while running my tests, and read changelogs and deprecation list from django docs but without any tip. -
Real Estate Project - Error in Pagination Code
I am a web developer student and I am currently working on a real estate project. I have created a pagination system that allows users to view a list of properties in pages of 10. However, I am getting an error when I try to load the second page of properties. The following is the code that I am using for the pagination: def get_properties(page_number): if page_number is None: page_number = 1 start_index = (page_number - 1) * 10 end_index = start_index + 10 properties = Property.objects.all().order_by('-list_date')[start_index:end_index] return properties The error that I am getting is: Page Not Found (404) The requested page could not be found. I have tried debugging the code, but I cannot seem to find the source of the error. I am hoping that someone can help me troubleshoot this issue. -
Nginx + Gunicorn + Django: displays Nginx default page every 3 times
I have a Django app on Gunicorn 20.1.0 (:8000), served with Nginx 1.18.0 as the main server (link to the website) on Debian 11.2: Nginx <-:8000-> Gunicorn <-> Django The server displays the Nginx default template every three times (1st request, 4, 7, 10, so on). Here is a snippet of the Nginx access log (notice the pattern in the bytes sent): 89.xx.xxx.xx - - [05/Jul/2023:11:37:23 -0400] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:51 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:52 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:53 -0400] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:54 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:54 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" ... There's no error in Nginx or Gunicorn error.log files (both server and site specific logs are blank. previously I had some errors so I'm assured that the logging is … -
Issue with Google Sign-In using Django-allauth and React
I am using bellow development environment: OS = Ubuntu 22.04.2 Python = 3.10.6 Django = 4.2.2 djangorestframework = 3.14.0 django-allauth = 0.54.0 I am running the the Django server on localhost 8000 with SSL and the React server on 3000 The authentication is being handled by django-allauth and I am only using google and the local a local model for authentication. I have registered both the front-end and back-end URLs with google credentials. The Google credential configuration looks like google credential configuration I am running the server with gunicorn with below command: gunicorn --certfile=certs/server.crt --keyfile=certs/server.key mt_backend.wsgi:application When I try to login with google using the URL: /accounts/google/login/. I am able login successfully. However when I try to POST the request to the same endpoint from my react app it throws 304(Forbidden) error with backend logging: Forbidden (CSRF cookie not set.): /accounts/google/login/ Here's the code snippet for login function used in react app: const handleGoogleLogin = () => { axios .post("https://127.0.0.1:8000/accounts/google/login/") .then((response) => { console.log(response); }) .catch((error) => { console.error(error); }); }; I have tried compare both the session and found out, there is one additional csrfmiddlewaretoken getting passed on paylod when I tried to use the django url , but … -
Permission Denied Nginx CSS File Django-Gunicorn Local VM
can helpme? My application in django does not load the css when I use gunicorn + nginx below I have permission error: 2023/07/05 16:29:51 [error] 18862#18862: *1 open() "/home/victor/helpme/tickets/static/css/style.css" failed (13: Permission denied), client: 192.168.0.106, server: 192.168.0.113, request: "GET /static/css/style.css HTTP/1.1", host: "192.168.0.113", referrer: "http://192.168.0.113/ticket_list/" My socket file: [Unit] Description=gunicorn helpme socket [Socket] ListenStream=/run/gunicorn_helpme.sock [Install] WantedBy=sockets.target ~ ~ ~ My Service File: [Unit] Description=gunicorn daemon Requires=gunicorn_helpme.socket After=network.target [Service] User=victor Group=www-data WorkingDirectory=/home/victor/helpme ExecStart=/home/victor/helpme/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn_helpme.sock \ ticket_system.wsgi:application [Install] WantedBy=multi-user.target Nginx: ps auxf | grep nginx victor 18883 0.0 0.0 6476 2308 pts/0 S+ 16:34 0:00 | \_ grep --color=auto nginx root 18860 0.0 0.0 55196 1716 ? Ss 16:29 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 18861 0.0 0.2 55864 5596 ? S 16:29 0:00 \_ nginx: worker process www-data 18862 0.0 0.2 55864 5596 ? S 16:29 0:00 \_ nginx: worker process Sites-enabled server { listen 80; listen [::]:80; index index.html index.htm index.nginx-debian.html index.php; server_name 192.168.0.113; location /static/ { root /home/victor/helpme/tickets; } location /media { alias /home/victor/helpme/tickets/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn_helpme.sock; } location ~ /\.ht { deny all; } location ~ /\. { access_log off; … -
Having error during adding a search feature in my ecommerce Django website
I put this command to my powershell: python manage.py startapp search And I am getiing this error again again: Traceback (most recent call last): File "C:\Users\ASUS\OneDrive\Desktop\Django_Prac\Hello\manage.py", line 22, in <module> main() File "C:\Users\ASUS\OneDrive\Desktop\Django_Prac\Hello\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'search' What can I do now? Please help! I want to know how to troubleshoot this? -
Django StreamingHttpResponse not streaming on production API
I'm trying to stream an OpenAI response from a Django server to the browser. I have a view in Django that looks like this (assume that generate_thing returns a stream from OpenAI): @api_view(['POST']) def generate(request): data = json.loads(request.body.decode('utf-8')) result = generate_thing(data) return StreamingHttpResponse(result) Whenever I run this locally, it works exactly as expected. When I upload my Django code to EC2 and try to call it directly on its IP address, it works exactly as expected. However, when I run it through a proxy like API Gateway or Nginx, it waits until the stream has completely finished to return a response. I tried setting Content-Type to text/event-stream before returning it like response = StreamingHttpResponse(result) response['Content-Type'] = 'text/event-stream' return response and it had no effect. -
Preload unique related object in Django
This works just fine and only performs one DB query: qs = Blog.objects.filter(post=Subquery( Post.objects.filter(blog=OuterRef("pk")) .order_by("-date").values("pk")[:1] )) for bt, pt in qs.values_list("title", "post__title"): print(f"The latest post in {bt} is about {pt}") However, how can I have Django construct Blog and Post objects out of such a queryset without needing additional queries? Something like the following: for blog in qs.select_related("post"): print(f"The latest post in {blog.title} is about {blog.post.title}") Assume it’s not possible to reverse the queryset (Post.objects.select_related("blog")), because, for example, there are other related models that need the same treatment as Post. -
Export df to csv in Django
I am new to Django I currently already have a df in the views.py, I pull the data from the MSSQL database which already connected. Views.py def CaseTest(request) dfa_query=""" Select * from database """ dfa=pandas.read_sql_query(dfa_query,connection) dfa_html=dfa.to_html(index=False,table_id='dbtable") return render(request,'CaseTest.html') CaseTest.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CaseTest</title> </head> <body> {% load site_extra %} <h2> CaseTest DF </h2> <div style="height: 500px; overflow: auto;"> {{itba | safe}} </div> </body> I want to add a button to html, when the user click it, they can download the df. How can I realize this. Any help is really appreciated! -
Python FileNotFoundError even though file is in same directory
I'm trying to use pickle to load a file within the same directory but I am getting FileNotFoundError for some reason. This is my code in views.py: from django.shortcuts import render from django.http import HttpResponse from django.core.files.storage import FileSystemStorage import pickle model = pickle.load(open('braintumor.pkl', 'rb')) def say_hello(request): return render(request, 'hello.html', {'name:': 'Alisha'}) def index(request): return render(request, 'index.html', { 'a' : 1}) And this is my file structure: webapp views.py braintumor.pkl It's a django app so is more complex than this but it wasn't important to list every file and directory, there is definitely no spelling errors and the pkl file is definitely in the same directory as views.py. I also tried a file structure like this: webapp views.py models -braintumor.pkl And then I tried using the import statement: "from models import braintumor" but that didn't work because I got an error saying that there is no such file or directory 'models'. I also tried loading it with the statement: "model = pickle.load(open('models/braintumor.pkl', 'rb'))" but still get FileNotFoundError! It seems no matter what I do, python simply cannot load anything and I have no idea what to do. I see nothing wrong with any of the solutions I tried. Please help, … -
Tests - both classes share the same login code but it only works in one
I'm writing tests for locallibrary app following the tutorial on MDN. Both classes that test views share similar login code, but it only works in one class I tried finding spelling errors and comping both classes Code snippets: Login throws FAIL: class AuthorCreateViewTest(TestCase): def setUp(self): # Create two users test_user1 = User.objects.create_user(username='testuser1', password='fjo&*&d3h') test_user2 = User.objects.create_user(username='testuser2', password='J9cdj8we9') test_user1.save() # Give test_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() def test_view_url_accessible_by_name(self): login = self.client.login(username='testuser2', password='J9cdj8we9') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 200) Login works: class RenewBookInstancesViewTest(TestCase): def setUp(self): # Create two users test_user1 = User.objects.create_user(username='testuser1', password='fjo&*&d3h') test_user2 = User.objects.create_user(username='testuser2', password='J9cdj8we9') test_user1.save() test_user2.save() # Give test_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() def test_logged_in_with_permission_borrowed_book(self): login = self.client.login(username='testuser2', password='J9cdj8we9') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance2.pk})) # Check that it lets us login - this is our book and we have the right permissions. self.assertEqual(response.status_code, 200) Here is the github link with all code in classes -
Is session always saved in Django?
The doc says below in When sessions are saved. *I use Django 4.2.1: By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted: But according to my experiment of the example in When sessions are saved, the session is always saved as shown below: # "views.py" from django.http import HttpResponse def test(request): request.session["foo"] = "bar" print(request.session.get('foo')) # bar del request.session["foo"] print(request.session.get('foo')) # None request.session["foo"] = {} print(request.session.get('foo')) # {} request.session["foo"]["bar"] = "baz" print(request.session.get('foo')) # {'bar': 'baz'} return HttpResponse('Test') Actually, I don't use the code below: request.session.modified = True And, SESSION_SAVE_EVERY_REQUEST is False by default and I don't even set it True in settings.py: SESSION_SAVE_EVERY_REQUEST = False So, is session always saved in Django? -
quickfix in django Execute multiple functions
When I run the code, it executes the command and opens the incomming file, but I cannot implement any other function. The file does not exist or cannot be opened. ` import time import quickfix import quickfix44 from django.shortcuts import render from django.shortcuts import render import threading from django.http import JsonResponse from quickfix import Message, MsgType from django.views.decorators.csrf import csrf_exempt symbol=['EURUSD', 'NZDAUD'] messages=[] messages1=[] messages2=[] should_stop_data_flow = True def messageToString(message): ............ def securityListRequest(sessionID): ............... def marketDataRequest(sessionID): ............ class Application(quickfix.Application): def __init__(self): super().__init__() def onCreate(self, sessionID): print("onCreate:") self.session_id = sessionID target = sessionID.getTargetCompID().getString() sender = sessionID.getSenderCompID().getString() return def onLogon(self, sessionID): self.sessionID = sessionID print("onLogon:", f"Session ID: {self.sessionID}") message = marketDataRequest(sessionID) print("market data request:", messageToString(message)) quickfix.Session.sendToTarget(message, sessionID) def onLogout(self, sessionID): print("onLogout..") return def toAdmin(self, message, sessionID): print("toAdmin:", messageToString(message), '\n') return def toApp(self, message, sessionID): print("toApp:", messageToString(message), '\n') return def fromAdmin(self, message, sessionID): print("fromAdmin:", messageToString(message), '\n') return def fromApp( self,message, sessionID): msg = messageToString(message) print("fromApp:", msg, '\n') def keepAlive(self): while True: time.sleep(30) def run_fix(): global app settings = quickfix.SessionSettings("CCFIX.ini") app = Application() storeFactory = quickfix.FileStoreFactory(settings) logFactory = quickfix.FileLogFactory(settings) initiator = quickfix.SocketInitiator(app, storeFactory, settings, logFactory) initiator.start() app.keepAlive() def start_fix_thread(): fix_thread = threading.Thread(target=run_fix) fix_thread.start() def fix_example_view(request): global symbol start_fix_thread() return render(request, 'show_messages.html', {'messages': messages})` -
Django on Airflow with remote logs: DAG stuck
I try running Django on Apache Airflow following this idea of a custom operator. When I use the default logging configuration, i.e. AIRFLOW__LOGGING__REMOTE_LOGGING=False, everything works as expected. However, when I now use remote logging with CloudWatch, the DAG seems to be stuck when Django starts to configure logging as invoked by django.setup(). I can confirm that logging to CloudWatch itself works as I have added a few logging events. *** Reading remote log from Cloudwatch log_group: job-sentinel-image-layer-log-group-5f303da log_stream: dag_id=clear_tokens/run_id=scheduled__2023-07-03T22_00_00+00_00/task_id=execute_clear_tokens_command/attempt=1.log. [2023-07-05, 17:23:27 CEST] Dependencies all met for dep_context=non-requeueable deps ti=<TaskInstance: clear_tokens.execute_clear_tokens_command scheduled__2023-07-03T22:00:00+00:00 [queued]> [2023-07-05, 17:23:27 CEST] Dependencies all met for dep_context=requeueable deps ti=<TaskInstance: clear_tokens.execute_clear_tokens_command scheduled__2023-07-03T22:00:00+00:00 [queued]> [2023-07-05, 17:23:27 CEST] -------------------------------------------------------------------------------- [2023-07-05, 17:23:27 CEST] Starting attempt 1 of 2 [2023-07-05, 17:23:27 CEST] -------------------------------------------------------------------------------- [2023-07-05, 17:23:27 CEST] Executing <Task(DjangoOperator): execute_clear_tokens_command> on 2023-07-03 22:00:00+00:00 [2023-07-05, 17:23:27 CEST] Started process 24150 to run task [2023-07-05, 17:23:27 CEST] Running: ['airflow', 'tasks', 'run', 'clear_tokens', 'execute_clear_tokens_command', 'scheduled__2023-07-03T22:00:00+00:00', '--job-id', '3', '--raw', '--subdir', 'DAGS_FOLDER/management_commands/src/clear_tokens.py', '--cfg-path', '/tmp/tmpkmehxuz0'] [2023-07-05, 17:23:27 CEST] Job 3: Subtask execute_clear_tokens_command [2023-07-05, 17:23:28 CEST] Running <TaskInstance: clear_tokens.execute_clear_tokens_command scheduled__2023-07-03T22:00:00+00:00 [running]> on host 147b23cea447 [2023-07-05, 17:23:28 CEST] Exporting the following env vars: AIRFLOW_CTX_DAG_ID=clear_tokens AIRFLOW_CTX_TASK_ID=execute_clear_tokens_command AIRFLOW_CTX_EXECUTION_DATE=2023-07-03T22:00:00+00:00 AIRFLOW_CTX_TRY_NUMBER=1 AIRFLOW_CTX_DAG_RUN_ID=scheduled__2023-07-03T22:00:00+00:00 [2023-07-05, 17:23:28 CEST] We are in pre-execute [2023-07-05, 17:23:28 CEST] after import of … -
Django User Avatar image is not getting reflected in media directory
I'm using django 3.2 on my GCP Ubuntu VM. My media folder as defined in my settings.py is ./media While as a user, I'm able to upload blog posts that contain images and the blog images show up inside ./media/blog but the profile picture(avatar) doesn't get uploaded to the .media/user directory. I get the following trace on my docker-compose when I click Save from my flutter front end to update the Profile picture. "PATCH /api/auth/user/ HTTP/1.1" 200 852 There is no error on my frontend so I'm troubleshooting the backend. The profile avatar details doesn't reflect even inside the auth directory under my username. Besides, On the frontend. The profile pic gets shown inside the profile box after upload but it fails(Nothing happens) when I click save and the profile box is again empty. This is something that I'm not able to figure on my own. Since this is related to both Flutter and Django , I'm uploading the avatar file flutter code below: if (avatarFile != null) { finalAvatarImage = FadeInImage( fit: BoxFit.cover, height: avatarSize, width: avatarSize, placeholder: const AssetImage(DEFAULT_AVATAR_ASSET), image: FileImage(File(avatarFile!.path!)), ); } else if (avatarUrl != null) { finalAvatarImage = Image( height: avatarSize, width: avatarSize, fit: BoxFit.cover, … -
Getting 500 internel server error while deploying django application inside digital ocean
I have been trying to deploy django application inside digital ocean ubunut vps for 12 hours. But can't solve this issue. Everything running just fine gunicorn, nginx eveyrhting looks good but still getting this error. Even tried to run it using my ip address:8000 and it ran well also. Here is the status of gunicorn: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2023-07-05 14:28:46 UTC; 1h 0min ago TriggeredBy: ● gunicorn.socket Main PID: 159720 (gunicorn) Tasks: 4 (limit: 1116) Memory: 258.2M CPU: 45.358s CGroup: /system.slice/gunicorn.service ├─159720 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application ├─159721 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application ├─159722 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application └─159723 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/chrome/webdriver.py", line 49, in __init__ Jul 05 15:16:59 scrapper gunicorn[159722]: super().__init__( Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/chromium/webdriver.py", line 51, in __init__ Jul 05 15:16:59 scrapper gunicorn[159722]: self.service.start() Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 97, in start Jul 05 15:16:59 scrapper gunicorn[159722]: self.assert_process_still_running() Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 110, in assert_process_still_running Jul 05 15:16:59 … -
How to use the Mapbox Search API with django
I have a previous question that this question follows: How to implement a mapbox search box. So now I have implemented the search box, how do I use the API to be able to retrieve detailed information on the address on the place of interest such as longitude and latitude -
Hide fields from SearchForm depending on the request user groups
I have a StockSearchForm: class StockSearchForm(CustomForm): component__code__icontains = forms.CharField(label=_('component code'), required=False) component__name__icontains = forms.CharField(label=_('component name'), required=False) component__product__icontains = forms.ChoiceField( label=_('product'), required=False, choices=b_choice + PRODUCT_CHOICES) inventory = forms.BooleanField(label=_('to inventory'), required=False) def __init__(self, *args, **kwargs): super(StockSearchForm, self).__init__(*args, **kwargs) self.fields[ 'component__code__icontains'].widget.attrs[ 'class'] = 'form-control' self.fields[ 'component__name__icontains'].widget.attrs[ 'class'] = 'form-control' self.fields[ 'component__product__icontains'].widget.attrs[ 'class'] = 'form-control' self.fields['inventory'].widget.attrs['class'] = 'btn pull-left' self.fields['inventory'].initial = False The field that is named inventory I only need to display it if the request user has groups "Administrator" or "Purchasing". I tried many codes that I found but neither works, can someone how to do it? I tried doing if not request.user.groups.filter(name__in["Admnistrator", "Purchasing"]).exists(): del self.fields['inventory'] and even self.fields['inventory'].widget = forms.HiddenInput() but nothing works for me (I know that I'm not setting request as a parameter, but I tried setting it obviously even user as a parameter -
I see less than half of the number of push notification sent on firebase dashboard than number we actual send daily using pyfcm library
E.g. We send more than 5 lakh push notifications daily but only 1.5 lakh messages sent on that day shown in Firebase dashboard. I want to know why firebase dashboard analytics not giving correct number for messages sent daily and how can i fix this issue -
How to implement "notification" for receiving messages from a conversation partner
I have implemented a simple messenger. How can I implement a "notification" system for receiving messages from a conversation partner? For example, when User 2 sends a message to User 1, User 1 should see a notification icon indicating an unread message, and the chat with User 2 should move to the top of the list, all without page reload. I believe this can be done using signals, websockets, and Django Channels, but I'm not sure how to proceed. i tried using signals and websocket -
Django 4.2 Window + Lag function does not assess lag properly: only 0's returned
I am trying to calculate lag with Lag window function and use field reference so that I can refer to it later in Case When clause. I am using MySQL 8.0.32. Here's something similar to what I have contrived: class Foo(models.Model): bar = models.ForeignKey('self', on_delete=models.CASCADE) baz = models.IntegerField() def my_method(self): foos = self.foo_set.annotate(lag=Window( expression=Lag('baz', default=0), order_by=F('baz').asc() )).annotate(output=F('baz')-F('lag')) for i in foos: print(i.pk, i.output) # desired result. But I can't use F('output') subquery = Subquery( self.foo_set.annotate( lag=F('baz') - Window( expression=Lag('baz', default=0), order_by=F('baz').asc(), ) ).filter(pk=OuterRef('pk')).values('lag') ) foos = self.foo_set.annotate(output=subquery) reference = F('output') for i in foos: print(i.baz, i.output) # not desirable As commented, the problem with the first foos is that I can't use field reference with F. When I try, it says lag function is not for this context: (django.db.utils.OperationalError: (3593, "You cannot use the window function 'lag' in this context.'") On the other hand, for the second foos, Window function only returns 0's. With F('baz'), I get nothing subtracted from baz. Example for Extra Clarification Let's say that I have four instances of Foo: A, B, C, and D. A is the bar of B, C, and D. baz for B, C, and D is 2, 3, and 4 respectively. … -
Django: How to identify if object is connected through ManyToManyField?
A basic representation from my models: class CarType(models.Model): name = models.CharField(max_length=200) class Brand(models.Model): name = models.CharField(max_length=200) cartype = models.ManyToManyField(CarType) class Customer(models.Model): name = models.CharField(max_length=200) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) I have a search function where the CarType is readily provided. I would have this object by it's ID. The customer is connected to the brand, which has manytomany to cartype (please ignore the models in this case, they are for illustration purpose). In my query, I only want to return those customers, which are connected to a brand, which on its turn has a relation with the cartype from a many-to-many relationship. So basically; how do I filter the customers to show only those, where the brand has a relation with the cartype? What my current thought is: Is it possible to create a modelmanager of some sort, which accepts the CarType as argument and return all relevant customers Create a second model for customers, where records are stored with a foreignkey directly to cartype (perhaps trigger this when a customer is added) Add a manytomanyfield for CarType to Customer, which automatically creates all the manytomany relations based on the existing records available in brand (and run a cronjob to review/update …