Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
django update model and preventing full table lock
Im using django 4.0.0. I have a model with an touched column (DateTimeField) to specify when a specific row was "touched" (like the unix command). I want to write a management command that updates this column to now() like so MyModel.objects.all().update(touched=now()) but the numbers of rows is large and i DON'T want to have a full table lock for this. Is there any way to have django update the queryset in multiple batches - each batch in a DIFFERENT TRANSACTION? or is there anyway to split my queryset to do this manually? -
How to implement a mapbox search box
I am struggling to implement a single map box search box into my project. I have a form and an input box that I would like to show POI suggestions. I do not want the mapbox search box to make my webpage scroll and I have tried to control it with the html/css but I believe I have to control the search box itself but I do not know how to do this. Please help I have tried to copy this example: https://docs.mapbox.com/mapbox-search-js/example/theming/ But it still is not working because I have to use "autocomplete=street-address" this means there is no POI suggestions being shown only addresses. Finally after I have got the input of the user I would like what they click as a suggestion to be passed to the API so my backend function can get the information such as latitude and longitude -
Django admin StackedInline throws (admin.E202) 'accounts.CustomUser' has no field named 'user' error
I have a CustomUser model, and a Retailer model that holds the additional details of retailer user type. The Retailer model has a OneToOne relation to CustomUser model. There is no public user registration or signup, accounts are created by superuser. In the Django admin site, I am trying to leverage admin.StackedInline in the retailer admin page to enable superusers to create new retailer users directly from the retailer admin page. This eliminates the need to create a new user object separately in the CustomUser model admin page and then associate it with a retailer object using the default dropdown in the retailer model admin page. However, I got the below error: MODELS.PY class CustomUser(AbstractUser): """ Extended custom user model. """ uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None # type: ignore first_name = None # type: ignore last_name = None # type: ignore name = models.CharField(_("Name of User"), max_length=150) email = models.EmailField(_("Email address of User"), unique=True, blank=False) date_modified = models.DateTimeField(auto_now=True) # Flags for user types is_retailer = models.BooleanField( _("Retailer status"), default=False, help_text=_("Designates whether the user should treated as retailer"), ) is_shop_owner = models.BooleanField( _("Shop owner status"), default=False, help_text=_("Designates whether the user should treated as shop owner"), ) USERNAME_FIELD = … -
How to upload image to cloudinary without creating a model in Django
I am building a website using Django. There is a Website and there is a server. Website communicates to server using API. I dont want the website to use any database (I want all data to be stored at the server). I want to upload images to cloudinary however couldn't figure out how to upload an image to cloudinary without creating a model in website. My website has an image upload location and when a user uploads an image, i want to upload that image to cloudinary directly and then retrieve the url of the image and send this url to server with api. Sending to server and uploading is fine, i can do that. But how can i upload to cloudinary and retrieve the url of the uploaded image in the same view function without creating a model or storing any data on the database (i will store it on the server's database) Thanks. I was able to upload images to cloudinary and retrieve the url however i was only able to do this by creating a model and saving it to the database. I don't want to create a model and save to the database. I just want … -
How to mock test a function inside save method
I want to send an email each time the status of an object was equal to 13. def save(self, *args, **kwargs): from user_profile.models import SopResumeBuy if skip_sop_resume := kwargs.get('skip_sop_resume'): del kwargs['skip_sop_resume'] if(self.status == 13): email_sender( "subject", f"email body", ) ...... the save method will call another email_sender which is a function inside another file. I want to make sure that the email will be sent.How can i mock the process of sending email?