Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Date Converter app in django views.py is running same time, i would like post method to run after user click only
I have created views.py for BS to AD date converter but my views will run only the UserInputForm() get loaded first, i have to comment post method then input data from frontend then again uncomment my post method views to get converted data. Please help me to fix by running first UserInputForm() then after click need to go thought the post method views.py from django.shortcuts import render from pyBSDate import convert_BS_to_AD from . forms import UserInputForms # Create your views here. def neview(request): # todays's date fm = UserInputForms() if request.method == 'POST': data = request.POST.get('date') up = data.replace('-',',') y = up[0:4] m = up[6:7] d = up[8:10] ad_data = convert_BS_to_AD(y, m, d) return render(request, 'NEC/NepaliToEnglish.html', {'fmr': fm, 'dt': ad_data}) html page {% extends 'NEC/base.html' %} {% block title %} Mid-West University Date Conveter App {% endblock title %} {% block content %} <h1>Welcome to Mid-West University Date Converter Application</h1> <h1>BS to AD Date Converter YYYY-MM-DD</h1> <form action="" method="post"> {% csrf_token %} {{fmr}} <br /> <br /> <input type="submit" /> </form> {{dt}} {% endblock content %} -
Subquery a Parent Model returning Error in Django
class Customer(models.Model): pass class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') total_amount = models.DecimalField() As you can see, a customer can have many orders. What I want to know, how much amount one customer has spent so far. qs = Customer.objects.get(pk=OuterRef('customer').orders.all().aggregate(total=Sum('total_amount)) Order.objects.annotate(customer_total=Subquery(qs.values('total')[:1])) But I am getting error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. My question is, can we Subquery a parent Model ? or i am doing something wrong ? -
Is it possible for Django to sum non numetric field?
I have learned we can sum all(or filtered) columns like price from this question. ItemPrice.objects.aggregate(Sum('price')) But is it possible for Django to sum non numetric field's length, such as CharField or JSONField? A pseudocode is like following. User.objects.aggregate(Sum(len('username'))) -
Please configure the inventory detail for item
I am trying to create an item fulfillment for an item , the on hand quantity on item fulfillment record is showing as X for that item at that location , but when it says configure inventory details for line X i am not able to see available under the status column I tried creating a saved search and getting the item's on hand greater than zero and location in the results but got as empty I also checked previous item fulfillments for that item they are created successfully with on hand quantity but now i am getting error as - Please configure the inventory detail for item -
Should i use different servers for backend and api provider?
I'm building an app in which I'm using react as frontend. And now I need to provide data from APIs, now my question is should I create a new server for APIs? Can anybody suggest to me how can I do this? BTW I'm using Django-restframework to interact with React. -
set optional parameter in a django url how can do this
I have write down this code in a url path('list/<str:name>', GetList.as_view(), name = "getList" ) now i want to set name as optional parameter with list it show show all and with name i will implement query -
Django manage stream response from StreamingHttpResponse
I met a problem when create stream video from Django server. generator_list = [] @gzip.gzip_page def get_stream_video(request, stream_link): if len(generator_list) == 2: generator_list[1].close() del(generator_list[1]) try: generator = detect_stream(stream_link) generator_list.append(generator) stream = StreamingHttpResponse(, content_type="multipart/x-mixed-replace;boundary=frame") return stream except: pass Everytime I call this controller from client, it will create new instance of connection. Then I found that if those streaming response not closed, CPU will load more and more. I try to save stream generator and close but it did not work. -
Could I make a Django project in ubuntu by Java?
Well... In my toy project, I want to make a Django project in ubuntu server by java ` ProcessBuilder builder = new ProcessBuilder(); builer.command("sh","-c","django-admin startproject helloWorld"); builder.directory(/home/ubuntu/toy_service); try { builder.start(); } catch(IOException e) {e.getMessage();} ` I check process builder activate command such as touch, ls, cd etc... But django-admin never activate ever. I check django is installed on my server How can I make a django project? Sorry for my fool English expected ProcessBuilder builder = new ProcessBuilder(); builer.command("sh","-c","django-admin startproject helloWorld"); builder.directory(/home/ubuntu/toy_service); try { builder.start(); } catch(IOException e) {e.getMessage();} happen nothing -
python django intercepting an sql query before it is executed
I have a library that natively crashes into django and works with django Admin and knows how to use objects.all() and so on. The QuerySet goes instead of to the database location in another api project. I need to intercept an sql query before executing which django does so that I can do even more magic with queries. maybe someone knows how to do it in theory ? well, or there is an example I will be glad to see. у меня есть библиотека которая нативно врезается в django и работает с django Admin и умеет использовать objects.all() и тд. Сам QuerySet в место базы данных ходит в другой проект по api. мне нужно перехватить sql запрос до выполнения который делает django что бы я мог делать еще больше магии с запросами. может кто то знает как это в теории сделать ? ну или есть пример буду рад увидеть. I tried to look for something similar on the Internet, but everywhere there is information only for outputting information to the logs about executed requests through Middleware я пробовал искать что то подобное в интернете но везде есть информация только на вывод в логи информацию о выполненных запросах через Middleware -
pylint with Django settings not working in vscode
I am attempting to configure pylint to use in my Django project. However, in VS Code it does not seem to be working when I configure my settings.json. For example, my settings.json is as follows: { "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.linting.pylintArgs": [ "--disable=C0111", "--load-plugins", "pylint_django", "--django-settings-module", "myproject.settings" ] } When I remove the two lines "--django-settings-module" and "myrpject.settings", pylint begins to work and throws linting errors. When I add the lines back, the linting errors go away (when they should actually be linting errors i.e. importing a package that isn't used). Below is my folder structure for the project I am working in. What could be the issue behind the django-settings-module? Why is it not registering when the argument is used? -
Django how to pass clicked on link text to a URL on another HTML page showing static images?
I have table of tickers on one HTML page, and four charts displayed on another HTML page. These charts come from my static/images folder full of hundreds of images named by ETF tickers. If I click the ETF ticker "PSCD" in the first row of the table, how can I have that linked in the other HTML page so that it shows only the images from my static/images folder whose filename contains the associated ticker...in this case "PSCD" when clicked. In the charts.html code example below, I hardcoded PSCD into the image tag but I want this dynamically linked. Below you will see my table.html page showing my table from above. Next is the charts.html where I would like the etf_ticker that was clicked in that table to be entered into the image tags such as <img src="{% static 'forecast/images/sample_regression_PSCD.jpg' %}" alt="sample_regression"/></div> where you see I have hardcoded "PSCD" into the image tag. But I need this to be dynamic, from which you click on the link in table.html, and it gets inserted into the image tag in charts.html. table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ETF Table</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}"> … -
Combining two serializer into one
I have a ListApiView where i list the data on a website and on the same page i could select the records and export to xl and pdf file here right now i am using same serializer called ListingSerializer for exporting the data to file and listing it, for listing the data and exporting the fields are same except for exporting i have two additional fields to be exported but right now i need two serializers one for listing ListingSerializer and other for exporting ExportSerializer without repeating the fields. class ListingSerializer(serializers.ModelSerializer): class Meta: model = Mymodel fields = '__all__' class ExportSerializer(serializer.ModelSerializer): date_records_received = serializers.SerializerMethodField() class Meta: model = Mymodel fields = '__all__' Class Mylist(ListAPIView): def get_queryset(): return queryset def get_serializer(): serializer = ListingSerializer(self.get_queryset(), many=True, context={'request': self.request}) return serializer -
When I access the page, nothing appears
question I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem? class Post(models.Model): created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False) title =models.CharField(max_length=255,blank=False,null=False) body =models.TextField(blank=True,null=False) def __str__(self): return self.title from Todolist import models from django.views.generic import ListView from django.utils import timezone class TodayView(ListView): model = models.Post template_name ='Todolist/today.html' def get_queryset(self): Today_list= models.Post.objects.filter( created=timezone.now()).order_by('-id') return Today_list {% extends "Todolist/base.html" %} {% block content %} {% for item in Today_list %} <tr> <td>{{item.title}}</td> </tr> {% endfor %} {% endblock %} urlpatterns=[ path('today/' ,views.TodayView.as_view() ,name='today')] -
Failed building wheel for psycopg2 (Windows 11)
I am building a Django project, and as I was installing the psycopg2(using virtual env), I kept getting an error. Versions: Django==4.1.2 Python==3.11.0 PIP==22.3 OS==Win11 Code: (env) PS C:\Users\keiko\Desktop\project> pip install psycopg2 Error: ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Failed to build psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure I have already tried the solutions I found on the internet like: Install psycopg2-binary instead. Code: pip install psycopg2-binary Error: Failed building wheel for psycopg2-binary Upgrade the wheel and setup tools Code: pip install --upgrade wheel pip install --upgrade setuptools pip install psycopg2 Install it with python Code: python -m pip install psycopg2 ERROR: Failed building wheel for psycopg2 Install the Microsoft C++ Build Tools ... but still none of these solutions helped me. I'm really hoping to install the package(psycopg2) on my project, I've been stuck with this error for so long and I can't really find any solution to this. I hope someone can help me with this. -
Beginner in Django, I would like to know how to retrieve the fields of the Consultation table starting from the Students table?
This is the error I get ProgrammingError at /Action/PassagePerso/19E000183/ operator does not exist: character varying = numeric LINE 1: ...on", public."Actions_students" WHERE matricule_id = 19E00018... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: http://127.0.0.1:8000/Action/PassagePerso/19E000183/ Django Version: 4.1.2 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = numeric LINE 1: ...on", public."Actions_students" WHERE matricule_id = 19E00018... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Exception Location: /home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/lib/python3.10/site-packages/django/db/backends/utils.py, line 89, in _execute Raised during: Actions.views.ConsultationPersonnelle Python Executable: /home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/bin/python Python Version: 3.10.4 Python Path: ['/home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/lib/python3.10/site-packages'] Server time: Wed, 02 Nov 2022 02:42:05 +0000 I would like to use the two tables Consultation and Students in relations to display the information of a person def ConsultationPersonnelle(request, pk_student): student = Students.objects.get(pk=pk_student) consult = Students.objects.raw(f'SELECT * from public."Actions_consultation", public."Actions_students" WHERE matricule_id = {student.matricule} and matricule = {student.matricule}') context = {'consultant': consult} return render(request, 'consult_perso.html', context) -
CSS files loaded but got not rendered Django Rest Framework
I have a Django app with Gunicorn and Nginx deployed on AWS ECS. NGINX can load static files but the page still shows only text. Nginx: server { listen 80; listen [::]:80; server_name api.example.com; location /health { access_log off; return 200; } proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; # Main app location / { if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE|PATCH)$) { return 405; } include /etc/nginx/mime.types; proxy_pass http://example-api:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header X-Forwarded-Port $http_x_forwarded_port; } location /static/ { autoindex on; alias /my_app/static/; } } In settings.py STATIC_URL = '/static/' STATIC_ROOT = '/my_app/static/' When I inspect the webpage, all CSS files are loaded, no 404 (It was an issue before but I fixed that). So not sure what else I am missing here. The UI works fine when running without Nginx and runserver, but on AWS ECS, I use gunicorn. -
How to use stored_procedure on Django Rest_framework
I'am trying to use my own stored_procedure to create an API of my own, it's purpose is to add an item into a table this is my raw Models.py class Clearanceinsert(models.Model): sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) this is currently my insert function def add(request): if request.method == "POST": if request.POST.get('sem') and request.POST.get('sy') saverec = Clearanceinsert() saverec.sem = request.POST.get('sem') saverec.sy = request.POST.get('sy') cursor = connection.cursor() userid = request.user.userid cursor.execute("select add_clearance_item_new('"+saverec.sem+"','"+saverec.sy+"') return HttpResponseRedirect('/Admin/index') else: return render(request, 'Admin/add.html') I did create an serializer class InsertItemSerialize(serializers.ModelSerializer): Class Meta: fields = ['sem','sy'] I remove some column so the code is shorter and easy to read, but this is basically it -
How to cache database tables in Django?
My app requires repetitive lookup a lot from same tables. Normally it should be design with foreign key to refer from table1 to table2, but there are no foreign keys design(yes db designed poorly). views look like this: class FileDownloaderSerializer(APIView): def get(self, request, **kwargs): filename = "All-users.csv" f = open(filename, 'w') datas = Userstable.objects.using(dbname).all() serializer = UserSerializer( datas, context={'sector': sector}, many=True) df=serializer.data df.to_csv(f, index=False, header=False) f.close() wrapper = FileWrapper(open(filename)) response = HttpResponse(wrapper, content_type='text/csv') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = "attachment; filename=%s" % filename return response this is my serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = Userstable fields = _all_ section=serializers.SerializerMethodField() def get_section(self, obj): return section.objects.using(dbname.get(pk=obj.sectionid).sectionname department =serializers.SerializerMethodField() def get_department(self, obj): return section.objects.using(dbname).get(pk=obj.deptid).deptname there are lots of table, more than 5 table, here I'm just showing 2 of them. Basically in the csv we need to import representable data. But in the main table, they only stored the id of the data, we need to get the actual representable data from the secondary table, hence the lookups. from the basics of programming. I understand that python normally cached variables that were being declared when a process runs, so the program doesn't have to go through declarations every time the variable is called. … -
Is there a way to filter a queryset with a field from another queryset in Django?
I am working on an endpoint that given a purhcase_id or a list of purchase_ids, it should return product_id and its related [info_ids], but in order to find the product_ids, I need to look into invoice table Data structure Invoice Table purhcase_id invoice_id Product Table product_id info_ids invoice_id Info Table info_id info_fields The input is purhcase_id, and purhcase_id has a 1:1 relationship to invoice_id, so that I should be able to do a lookup to get the invoice_id, and use that invoice_id to filter products + get its related info_ids, however, I am not sure how to do this in django properly with this nested relationship. -
Django return JsonResponse and continue
I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not def paytes(request): payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type_msg, "USERDATA": text, "SESSIONID": session_id, "MSG": response, } print('MSG: ',response) # headers = { # 'Content-Type': 'application/json' # } # response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) return JsonResponse(payload) url = 'https://prod.theteller.net/v1.1/transaction/process' transaction_id = random.randint(100000000000, 999999999999) amounte = "000000000080" amount = str(amounte) data = { "amount" :amount, "processing_code" : "000200", "transaction_id" : transaction_id, "desc" : "Mobile Money Payment Test", "merchant_id" : "TTM-00000727", "subscriber_number" : "233244491909", "r-switch" : "MTN", } encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=') # change this as well headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {encoded.decode("utf-8")}', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers) print(res.text) response_data = res.json() status = response_data["status"] print(response_data) print(status) return HttpResponse(res) -
How To Join Two Models with Different Column Names and Return All Instances?
I aim to create a dataframe of the Top 3 Selling menu_items in my Purchases table. My thoughts are to create a join on the Purchases model with the Menu_Item model where Purchases.menu_item = Menu_Item.title. I will convert the QuerySet to a DataFrame using django_pandas.io. I plan to use the sum of Menu_Item.price associated with each distinct Purchases.menu_item to determine the Top 3 menu_items of all the records in the Purchases table. My problem is that I cannot join the two tables successfully. I’ve scoured the interwebz for a working solution to join two models with different field names, which returns all instances, and I tried various solutions, but the scarce articles on this topic yielded no joy. models.py ... class MenuItem(models.Model): title = models.CharField(max_length=100, unique=True, verbose_name="Item Name") price = models.FloatField(default=0.00, verbose_name="Price") description = models.CharField(max_length=500, verbose_name="Item Description") def __str__(self): return f"title={self.title}; price={self.price}" def get_absolute_url(self): return "/menu" def available(self): return all(X.enough() for X in self.reciperequirement_set.all()) class Meta: ordering = ["title"] class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, verbose_name="Menu Item") timestamp = models.DateTimeField(auto_now_add=True, verbose_name="DateTime") def __str__(self): return f"menu_item=[{self.menu_item.__str__()}]; time={self.timestamp}" def get_absolute_url(self): return "/purchases" class Meta: ordering = ["menu_item"] I tried adapting too many unsuccessful code fragments to reproduce here, so I am looking … -
testdriven.io: The Definitive Guide to Celery and Django. Running task from Django shell causes error
I am currently going through 'The Definitive Guide to Celery and Django' course by testdriven.io. I've managed to containerize the whole application. Everything was built correctly and seemed to work just fine, but when I tried to enter the Django shell and run a task, to ensure everything works correctly, the following error appeared. >>> divide.delay(1, 2) Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.10/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/usr/local/lib/python3.10/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/celery/app/task.py", line 425, in delay return self.apply_async(args, kwargs) File … -
MMO Backend Architecture Questions and Review Request
I am making a simple MMO backend with Django as a personal/portfolio project. (I am not actually making an mmo game) You can find the project here So I have some questions for the architecture because I designed it 1. Architecture 1.1 Terminology AuthServer= Web Server responsible for the authentication UniverseServer= Web Server responsible for the persistent storage of the game (Couldn't find a better naming) MatchmakingServer= Web Server that acts as intermediary between the client and the GameServerManager GameServerManager= A cluster manager responsible for starting/stoping GameServerInstances GameServerInstance= An instance of the game server PlayerClient= The game client of the player 1.2 Flow 1.2.1 Authentication PlayerClient logins to AuthServer to obtain an AuthToken at /api/auth/login/ 1.2.2 Retrieving Player Data PlayerClient requests all the needed data from the UniverseServer at /api/universe/user/{...} (example: the characters list) 1.2.3 Connecting To A Game Server PlayerClient requests an available game server from the MatchmakingServer with some parameters The MatchmakingServer checks if there is an available GameServerInstance on the database with these parameters If there is an available GameServerInstance, the MatchmakingServer responds to the PlayerClient with the IP and the Port of the GameServerInstance, else it is gonna send a request to the GameServerManagerto spawn one … -
Django logging configuration star notation
Let's say I have the following Django logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers": { "django": { "handlers": ["console"], "level": "INFO", "propagate": False, }, "app1.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, "app2.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, "app3.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, }, } Notice how I'm repeating the same configuration for all app management commands. I'd love to be able to consolidate into a single entry like so: "*.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, } But this doesn't seem to work. Is this possible or do I need to repeat the config for all apps? -
Getting Celery tasks repeated multiple times in production
I'm new to Celery, and I created a simple app that connects to a web socket server to receive tasks and schedule them using Celery. My Celery queue display tasks based on the type of the message (text messages first, and then buttons that run the next task if one of them is clicked). Locally, everything run as expected. But, some tasks are repeated multiple times in production, especially the triggers (buttons). In my production environment, I created a web service for Django and one Celery background worker with a Redis database. Here are the commands I used to run Celery worker and beat in production: # Start command (celery worker and beat) celery -A bot.celery worker --beat --scheduler django --loglevel=info --concurrency 4 # Start command (Django) daphne -b 0.0.0.0 bot.asgi:application My Django and Celery settings: CELERY_BROKER_URL = "redis://localhost:6379/0" # localhost replaced with the internal Redis URL in production CELERY_RESULT_BACKEND = "redis://localhost:6379/1" # localhost replaced with the internal Redis URL in production TIME_ZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' ASGI_APPLICATION = 'bot.asgi.application' Some of the worker output: Nov 1 09:00:15 AM [2022-11-01 08:00:15,178: INFO/MainProcess] missed heartbeat from celery@srv-cdcl4202i3msb94icl70-5469f7b9d8-gzks7 Nov …