Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to bypass the TTL of 30 seconds while waiting response of post request from external server
I am building a view in Django , which will send a POST request to chat-gpt API, the problem that I am facing that the response from chat-gpt is taking more than 30 seconds (we are having a long prompts) the idea that I have in mind is: The client sends a request to the server. The server writes the request to a message queue and returns a message ID to the client. Another worker is listening to the message queue. It retrieves the request from the queue, sends it to OpenAI,and then writes the response back to the message queue. The client periodically sends requests to the server to ask for the response using the previously received message ID. The server responds with "pending" until it finds the response in the message queue, at which point it returns the actual response to the client. the problem is that I have no idea how to achieve that ... I am using gke for hosting the application, I already have some cronjob using some views as well any idea how to deal with this will be so much appreciated here is an example of the view request: import openai from app.forms_prompt … -
settings.py not retrieving Django-Environ info server side
my Issue Hello, I am having issues with my website fetching the information from my Django-envrion file to settings.py. I am able to open up localhost:8000 on my dev computer perfectly with the same configuration (just Debug set to off and using the local DB). Although when I boot up my server I have issues logging into postgres, Also debug is set to on despite the environment file being set to 0. There are also some oddities where it might fetch the Database name and Database user as those are in the environment files. Here is the error that shows up (despite debug is off like i mentioned prior although it can read some attributes I believe considiering it knows what database and the name for the user): OperationalError at / connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "DBuser" connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "DBuser" Request Method: GET Request URL: https://[REDACTED].com/ Django Version: 4.2.3 Exception Type: OperationalError Exception Value: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "DBuser" connection to server at "localhost" (::1), port … -
Django + React App: Getting 404 Errors for Static Files
I am currently working on a Django + React web application and I've encountered an issue with serving static files. The Django development server is returning 404 errors for several static files and images, like images "K5.png," "earth.png," and "manifest.json." Yes, the website loads, except for the images. This is how I refer to my images (example): <img src="/earth.png" alt="" className="earth w-fit mx-auto"/> I've configured my settings as follows: STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR_FRONTEND, 'frontend/build/'), ] import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR_BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR_FRONTEND = os.path.dirname(BASE_DIR_BACKEND) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Installed Application 'api', 'rest_framework', 'djongo', 'pymongo', "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_METHODS = ( "GET", ) ROOT_URLCONF = 'project_k5.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR_BACKEND, '../frontend/build')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
Reverse url fails with re_path after migrating to Django 4 from Django 2
After migrating to Djanogo 4 from Django 2 I started having issues with the reverse path urls in templates. The following error was thrown: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with arguments '('MQ', 'bwachb-fa5e0484e188dc10f2573f3eedf2dd11')' not found. 1 pattern(s) tried: ['en/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] I created a test case to reproduce this issue: def test_reverse_activation_url(self): url = reverse('activate', args=['MQ', 'bwachb-fa5e0484e188dc10f2573f3eedf2dd11']) self.assertEqual(url, "/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/") Originally the urlpatterns was like this, and I managed to reproduce the same error running the testcase. urlpatterns += i18n_patterns( Django2: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'), Django4: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'), ) If I change the urlspatters as follows: urlpatterns += i18n_patterns( re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})', core_views.activate, name='activate'), ) The test case will fail because of no trail slash: AssertionError: '/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11' != '/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/' - /en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11 + /en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/ ? + If I change the urlspatters as follows, the test will pass. urlpatterns += i18n_patterns( path('activate/<uidb64>/<token>/', core_views.activate, name='activate'), ) Why is there a difference in the link generated when using re_path and path? Mainly in this case the trail slash. I also tried: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/?$', core_views.activate, name='activate') Which results NoReverseMatch And: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/?', core_views.activate, name='activate') Which results in the link with no trail slash error. Can someone please shed some light into this? I already wasted so many hours... I am currently on Django==4.2.5 -
Django Rest Auth and Google Auth - Google does not store username and email
Currently I have a registration with Django Rest Auth where I implement a login with Google under an extended user model with AbstractUser, the problem is that when authenticating with Google, when the user registers it does not store the username and email of the email I entered With google. Any ideas? This is the AbstractUser model: class User(AbstractUser): full_name = CharField(_("Full Name"), max_length=255, null=True, blank=True) device_token = models.CharField(_("Device Token"), max_length=200, null=True, blank=True) cellphone = CharField(_("CellPhone"), max_length=15, null=True, blank=True) class Meta: verbose_name = "User" verbose_name_plural = "Users" def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) This is the example of a user who has logged in with Google, this is how the model looks in the database: Model User with Google Request with token user Whats is the problem? I hope that google stores the email and user at the time of registering in the Django database. -
Why I can't install django offline?
I have to install django on a company server that does not have Internet access. After downloading and installing ***pytz-2023.3.post1-py2.py3-none-any.whl*** I am able to install ***django*** from the .zip file. You might ask what's the point if I'm able to install it? Well, I can install django and the necessary libraries from the downloaded files only when the server is connected to the Internet. It turned out that the following libraries are necessary during installation: - asgiref-3.7.2-py3-none-any.whl - tzdata-2023.3-py2.py3-none-any.whl - sqlparse-0.4.4-py3-none-any.whl Of course, I downloaded and installed them without any problems. However, I still get an error when installing django. Below is the error code. C:\Users\Administrator\Downloads>py -m pip install django-stable-4.2.x.zip Processing c:\users\administrator\downloads\django-stable-4.2.x.zip Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [7 lines of output] WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000221F9E73C10>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/setuptools/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000221F9E7B4D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/setuptools/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection … -
How do I implement a button that navigates to the next question in Django if one question is displayed on a page?
Code and some explanations on how to do it in Django for a beginner. I tried to get the id of the question but I have no way of making it appear in the url because of the urls that route to the page have already been made and it took me some time to make the url work well after adding some other urls -
Displaying the sum of expenses in my dashboard page
Hello guys so I have an expense app that helps to keep track of all expenses in a project but I want to display the sum of all these expenses on the dashboard page so that when the user logs in they can see the total expenses of a particular project. I already have a html file (expenses.html) which shows a table of all expenses (but not the sum) so I was thinking maybe there is a way I can calculate the sum and incorporate it in the dashboard page. So here is how I tried doing it with no success; I created a model in my models.py (of the dashboard) class Expense(models.Model): amount = models.FloatField() Then went to my view.py (of the dashboard) to define a function called total_expenses. def total_expenses(request): total_expenses = Expense.objects.aggregate(total=Sum('amount')) return {'total_expenses': total_expenses['total']} After that I returned to the dashboard.html and wrote this; <div class="card mt-3"> <a class="nav-link" href="{% url 'expenses' %}"> <h5 class="card-category">Total Expenses</h5> <h2 class="card-title"> ({{ total_expenses }}) </h2> </a> </div> I want the sum to be displayed in the brackets as shown in the image provided; Tab to display the sum I know it is not a lot but I would appreciate … -
Python 3.11 - IIS 10 - AttributeError: Module has no attribute 'wsgi'
I have a Python (3.11) web application using Django 4.2.5 deployed to a Windows 2019 Server running IIS 10. I have deployed several Python + Django apps to IIS WebServers previously with no issues, however they were older versions (Windows 2016, python 3.8, django 3.2) I don't expect that much has changed since then so when deploying this application I mimicked the configuration of IIS, however it continues to give me the same error. I have all of the Windows Features installed (IIS, CGI, .Net 3.5 and 4, etc) I have configured the Environment Variables in the FastCGI settings (IIS WebServer level), and the Application Settings (on the site level) I have configured the Handler Mappings And yet no success. Hoping someone can help point me in the right direction. ** My Application Folder Structure (in case it's important) ** (https://i.stack.imgur.com/uNexE.png) In settings.py WSGI_APPLICATION = 'main.root.wsgi.application' In wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'root.settings') application = get_wsgi_application() I'm sorry if I left out any information that's relevant. This is my first post. -
How can I make a reservation for hours only? django
I have a reservation site. I want the reservation to be made in hours only. For example, I don't want anyone to book from 10:30 to 12:00. i want to be 10:00 to 12 or else just by hours enter image description here How can I remove this minute column or make it zero by zero? lock at the image my models is : from_hour = models.DateTimeField(default=datetime.datetime.now()) to_hour = models.DateTimeField(default=datetime.datetime.now()) my forms : class Meta: model = OpeningHours fields = ('from_hour', 'to_hour','timing',) widgets = { 'from_hour':forms.DateTimeInput(format=('%Y-%m-%dT%H:%M'),attrs={'type':'datetime-local','class':'form-control'}), 'to_hour':forms.DateTimeInput(format=('%Y-%m-%dT%H:%M'),attrs={'type':'datetime-local','class':'form-control'}), -
Django managed=False model save doing insert instead of update and failing for duplicate PK
I'm connected to a legacy database using PyODBC. Some models insert and update just fine, however this one doesn't. When we grab existing records using the ORM, it tries to do an insert on save instead of an update class PurchaseOrder(models.Model): purchaseorderid = models.BigAutoField(db_column='PurchaseOrderId', primary_key=True) ticketnumber = models.CharField(db_column='TicketNumber', unique=True, max_length=20, blank=True, null=True) customer = models.ForeignKey('Customer', to_field='local_id', db_column='CustId', on_delete=models.DO_NOTHING) # a bunch of other irrelevant columns class Meta: managed = False db_table = 'PurchaseOrders' In the shell (or code anywhere else) I can grab an existing PurchaseOrder and even print it's pk just fine: >>> po = PurchaseOrder.objects.all()[76543] # grab a random existing po >>> print(po.pk) 78730 But when I go to save the record, which should do an update -- we've verified the pk exists -- it tries to do an insert and fails due to duplicate pk: >>> po.save() Traceback (most recent call last): File "/home/django/.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/django/.env/lib/python3.10/site-packages/mssql/base.py", line 621, in execute return self.cursor.execute(sql, params) pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK_PurchaseOrders_1'. Cannot insert duplicate key in object 'dbo.PurchaseOrders'. The duplicate key value is (78730). (2627) (SQLExecDirectW)") If I change the model to use … -
Docker + Django + ElasticSearch: Failed to establish a connection
I'm having issues connecting ElasticSearch to Django while dockerizing my application. When I try to run my applicatiom using docker compose, i get the following error: elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPSConnection object at 0x7fc59132e890>: Failed to establish a new connection: [Errno 111] Connection refused)) Before building the containers, I followed this tutorial, adapting the packages to the versions I wanted. I was able to establish a connection between the Django App and a single-node cluster running on a docker container. I copied the SSL certificate from the ElasticSearch container to the Django app root, and defined the ELASTICSEARCH_DSL on Django settings as: ELASTICSEARCH_DSL = { 'default': { 'hosts': ['https://localhost:9200'], 'http_auth': ('elastic', 'password'), 'verify_certs': True, 'ca_certs' : './http_ca.crt', }, } After building the containers and creating a docker-compose.yml, I didn't find a way to extract the certificate to the Django container. I tried to establish a connection putting 'verify_certs': False but it didn't work. I tried to find a solution, but most of the time I found people using ElastiSsearch 7.x.x while I'm using version 8.10.1. Python Packages django==4.2.6 djangorestframework==3.14.0 django-cors-headers==4.3.0 elasticsearch==8.10.1 elasticsearch-dsl==8.9.0 django-elasticsearch-dsl==8.0 psycopg2-binary==2.9.9 docker-compose.yml version: '3.8' services: db: image: postgres:15.4-alpine3.18 volumes: - postgres_data:/var/lib/postgresql/data/ environment: … -
Django: adding a second 'detailed' view for retrieving extra information
I have set up my urls.py and views.py file to serialize my Projects model in two different ways: detailed information for the 'retrieve' action, and abbreviated information for the 'list' action. This works well so far: /projects/ = list of projects with abbreviated information /projects/12 = detailed information about a specific project (id=12) urls.py: router.register(r'projects', ProjectViewSet, basename='project') views.py class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializerMini # Select a serializer according to the action (i.e.: 'retrieve' will # return a more detailed serialized data than 'list') action_serializers = { 'retrieve': ProjectSerializerDetail, 'list': ProjectSerializerList } def get_serializer_class(self): return self.action_serializers.get(self.action, self.serializer_class) My question is: would it be possible, using the ViewSet framework, to summon a third serializer that would return, say, an even more detailed set of information. Ex.: /projects/12/extradetail The reason for this is that some of these records include geospatial data that is quite voluminous. I would only want to retrieve this extra detail in some cases -
django-simple-history only works in the admin interface
I am trying to get django-simple-history to work. It does work in the admin interface but not in my view code. I recreated the sample but it does not work for me. Models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') history = HistoricalRecords() class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) history = HistoricalRecords() view: def main_view(request): p = Poll.objects.first() p.question = 'Test' p.save() return HttpResponse('done') It won't create a history entry when i call the view. If u change it in the admin interface i do get a changed entry. Does anyone know what i am doing wrong. Using: Django==4.2.6 django-simple-history==3.4.0 -
How I can use singleton with rabbitmq django celery?
I cannot find a solution. But I found realization on Redis. https://github.com/steinitzu/celery-singleton Please send me the Singleton realization with RabbitMQ if you have. Example: @shared_task(base=SomeSingleton): def some_task(): """deliver or count something""" -
django rest serializer to_representation failing
Im messing around with django rest framework and its serializers, and im running into an error when overriding the create method. serializer class AdddTestModel(serializers.Serializer): name = serializers.CharField() score = serializers.FloatField() score2 = serializers.FloatField() song = serializers.IntegerField() def create(self, validated_data): print(validated_data["song"]) song = Song.objects.get(id=validated_data["song"]) print(song) instance = TestModel.objects.create(name=validated_data["name"], score = validated_data["score"], score2 = validated_data["score2"], song = song) return instance def to_representation(self, instance): representation = super().to_representation(instance) return representation View @api_view(["POST"]) def addTestModel(request): serializer = AdddTestModel(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.data) return Response("hello", status=status.HTTP_201_CREATED) return Response("Error", status=status.HTTP_401_UNAUTHORIZED) I had everything working correctly when I was using a modelSerializer, but wanted to experiment with serializer.Serializer. I know the create method is working as the TestModel object is being persisted into my db. The error seems to be coming from the to_representation method, specifically representation = super().to_representation(instance) The error i am getting is the following Internal Server Error: /api/addTest/ Traceback (most recent call last): File "C:\Users\thoma\Documents\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\thoma\Documents\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\thoma\Documents\venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\thoma\Documents\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 469, … -
How to update Model attributes in production
I have a django app which I deployed three years ago that has been working perfectly and making our life in the laboratory easier. Recently there was a need that wasn't contemplated in the beginning, and I have added some functionality to the app. This involved modifying some Model methods and some AdminModel methods as well. Unfortunately web development is not my field and this was a single thing that I did with Python in my spare time and now I'm not sure what will happen If I pull the changes from the repository. I remember that in development I had to use manage.py migrate manage.py makemigrations after any changes to the models attributes. In this case it's only methods that I have modified. Do I still need to run these commands in the production server? Will I loose data (this can not be tolerated)? I'm using the sqlite standard database that django generates by default. Thanks a lot in advance. -
React Items wont render using Router
I am using routes in a react/django app and I have components that will not render. This is my app.js which renders my homepage. import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./Homepage"; export default class App extends Component { constructor(props) { super(props); } render() { console.log("App Here"); return ( <HomePage /> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); This is my homepage.js: import React, { Component } from "react"; import RoomJoinPage from "./RoomJoinPage"; import { Routes, Route, BrowserRouter } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { console.log("homePage Here") return ( <BrowserRouter> <Routes> <Route path="/" element={<p>Test</p>} /> <Route path="/join" element={<RoomJoinPage />} /> </Routes> </BrowserRouter> ); } } And this is a component I am trying to render: import React from "react"; export default function RoomJoinPage() { console.log("RoomJoinPage component is rendering."); return <h1>Room Join Page</h1>; } I have it working with HTML, and have narrowed it down to the routing issue. Any insight would be helpful. Thanks! I have tried various different routing configurations. My versions are: "react": "^18.2.0", "react-router-dom": "^6.17.0". I would like the components to render on the correct routing. -
Database From An External API in Django
I am new to django I am trying to make an claorie tracker app in which, i want to fetch data from this api "https://api.api-ninjas.com/v1/nutrition?query=" but on checking my model it shows 0 objects.Iam not able to do it correctly, can someone tell me where is the issue and me solve it ` def index(request): if 'name' in request.GET: name = request.GET['name'] url = "https://api.api-ninjas.com/v1/nutrition?query=" + name headers = {'X-Api-Key': 'api key'} response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json().get('data', []) for item in data: FoodItem.objects.get_or_create( name=item['name'], calories=item['calories'], carbohydrates=item['carbohydrates_total_g'], protein=item['protein_g'], fat=item['fat_total_g'], fibre=item['fiber_g'] ) print('saved') else: print(f"Error: {response.status_code}") return render(request, 'food.html') from django.db import models from django.contrib.auth.models import User # Create your models here. class FoodItem(models.Model): name = models.CharField(max_length=255) calories = models.PositiveIntegerField() carbohydrates = models.FloatField() protein = models.FloatField() fibre = models.FloatField() fat = models.FloatField() date = models.DateField() def __str__(self): return self.food_item class UserFoodConsumption(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) food_item = models.ForeignKey(FoodItem, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) I want to store all information from api to my model "FoodItem" -
How to search multiple fields using objects.filter
I have the following 3 names in my db cid name email 1 | John Smith | jsmith@email.com 1 | June Bug | jbug@email.net 2 | Rick Ross | rross@email.com Is there a way to search 2 parameters as and 'OR' and the last parameter as an 'AND' so the query would be something like this if i pass it like 'm' and for it to search the name or email for the letter 'm', and the also passing it a '1' so that cid=1 So the result would come back as 1 | John Smith | jsmith@email.com 1 | June Bug | jbug@email.net And if i did the same search but passing it 'o', it would search the name or email for the letter 'o' and with cid=1 it would give me the following result 1 | John Smith | jsmith@email.com -
Trade-offs and considerations for conditional tuple unpacking in Python: primarily performance but also stylistic considerations for maintainability
I have a piece of logic in Python that involves tuple unpacking based on conditions. The code instantiates two variables, and assigns to these variables the unpacked values of a tuple. This tuple is defined conditionally: if a conditional_expression is true, then a function executes returning a tuple, else default values are provided and assigned. My understanding is there are two simple ways to implement this, as follows: # Method 1 # if conditional_expression: processed_data, context = tuple_returner(raw_data) else: processed_data, context = raw_data[0], None # Method 2 # processed_data, context = ( tuple_returner(raw_data) if conditional_expression else raw_data[0], None ) Now I have tried both ways, and both work well as expected. My question is two-fold: Is either method likely to be more performant than the other (in a standard CPython implementation)? I do not notice any substantial differences when running timeit tests (although method 2 seems ever so slightly faster), but I was wondering if anything deeper is happening under-the-hood that I'm not aware about. Is either method more Pythonic and generally preferred by the community than the other? I couldn't see anything specific inside PEP8 to guide me on this. Both seem readable to me but this code-base will … -
ORA-12170: TNS:Connect timeout occurred on docker container
Im building a project which connect to a oracleDB remotely using a VPN, the backend is python with django and I dockerized the project until fridays last week everything was working well, after that when i run docker compose up I get this error: django.db.utils.DatabaseError: ORA-12170: TNS:Connect timeout occurred The dockerfile has following structure: FROM python:3.10.12-alpine3.18 ENV PYTHONUNBUFFERED 1 RUN apk add --update --no-cache\ build-base jpeg-dev zlib-dev libjpeg\ gettext\ py3-lxml\ py3-pillow\ openldap-dev\ python3-dev\ gcompat\ && rm -rf /var/cache/apk/* RUN apk add --no-cache libaio libnsl libc6-compat curl bash WORKDIR /opt/oracle RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \ unzip instantclient-basiclite-linuxx64.zip && \ rm -f instantclient-basiclite-linuxx64.zip && \ cd instantclient* && \ rm -f *jdbc* *occi* *mysql* *jar uidrvci genezi adrci && \ mkdir /etc/ld.so.conf.d && \ echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf RUN ldconfig /etc/ld.so.conf.d ENV LD_LIBRARY_PATH=/opt/oracle/instantclient_21_11 ENV PATH=/opt/oracle/instantclient_21_11:$PATH RUN echo 'INPUT ( libldap.so )' > /usr/lib/libldap_r.so The DB connection is: DATABASES = { "default": { "ENGINE": "django.db.backends.oracle", "NAME": ( f"{env('DATABASE_SERVER')}:{env('DATABASE_PORT')}/{env('DATABASE_SERVICE_NAME')}" ), "USER": env("DATABASE_USER"), "PASSWORD": env("DATABASE_PASS"), } } What seems more strange to me is that I can perfectly connect to the DB via DBeaver (client) and another test is that I pinged the IP of the DB server and I have a response but, if … -
How to upadate a text for H2 tag from views.py in django
I have the buttons defined in html file. When I click on the button iam sending the name of the button using post request using Ajax and getting it to the views.py , saving it in 'catogory_type'. When iam printing it in the terminal, it is getting printed. But when iam rendering the page, that H2 tag is showing empty without any text. How can I print that value in the page when I clicked on the button. Asper my understanding, after clicking the button in the page, it is not getting reloaded. Iam not sure how to refresh the page to re-render it with updated data again. Please suggest me on this. Thanks:) Need to get the the page refresh with updated data in django. -
python django factory set random locale and then create model based on this locale
I would like to create test models of people of different nationalities. During creation, factory would randomly select nationality from a list of "locale" attributes. It would then determine personal attributes based on the previously drawn nationality. Here is my code, which does not work. It mixes attributes of different nationalities class PersonModelFactory(factory.django.DjangoModelFactory): locale = factory.fuzzy.FuzzyChoice(["cs_CZ", "da_DK", "de_DE", "en_GB", "es_ES", "fr_FR", "hr_HR", "hu_HU", "it_IT", "nl_NL", "no_NO", "pt_BR", "pt_PT", "ro_RO", "sk_SK", "fr_CH", "pl_PL", "de_AT", "es_AR"]) class Meta: model = Person exclude = ("locale",) first_name = factory.Faker("first_name_male", locale=locale) last_name = factory.Faker("last_name_male", locale=locale) nationality = factory.Faker("current_country", locale=locale) ...and so on... In addition, it would be best if half of the people could be British, another half as other mixed nationalities. I tried this code to do so: locale = factory.fuzzy.FuzzyChoice(["en_GB", None]) if locale is None: locale = factory.fuzzy.FuzzyChoice([...]) Unfortunately, only the first line of code is is read and the program only chooses between en_GB and None (which is en_US by default). If statement is ignored. -
I want Small Modal but my modalis not worrk properley as I want
<!-- Modal --> <div class="modal fade" id="deleteItemModal" tabindex="-1" role="dialog" aria-labelledby="deleteItemModalLabel" aria-hidden="true"> <div class="modal-sm modal-dialog " role="document"> </div> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body confirm-delete text-center" > <div class="alert" id="delete_item_alert"></div> <div id="modal-message"></div> <hr> <form action="" method="post" id="form_confirm_modal"> {% csrf_token %} <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmButtonModal">Delete</button> <button type="button" class="btn btn-primary" data-dismiss="modal">close</button> </form> <input type="hidden" id="address_suppress"/> </div> </div> </div> <div class="modal-body confirm-delete text-center" > <div class="alert" id="delete_item_alert"></div> <div id="modal-message"></div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', () => { let form_confirm = document.querySelector('#form_confirm_modal') let buttons = document.querySelectorAll("[data-target='#deleteItemModal']"); buttons.forEach(button => { button.addEventListener("click", () => { // extract texts from calling element and replace the modals texts with i if (button.dataset.message) { document.getElementById("modal-message").innerHTML = button.dataset.message; } // extract url from calling element and replace the modals texts with it if (button.dataset.url) { form_confirm.action = button.dataset.url; } }) }); let confirmModal = document.getElementById("confirmButtonModal") confirmModal.addEventListener('click', () => { form_confirm.submit(); }); }); </script> I want modal popup delete confirmation ,The modal is work properley but it is too large i need small modal. I have the above modal ,I use class .modal-sm but it doesnot work .please help me. I want modal popup delete confirmation ,The modal is work properley but it …