Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Programming Error: Cannot Cast Type bigint to uuid
I'm facing an issue while trying to change the data type of a column in my Django model from bigint to uuid in a PostgreSQL database. The error message I'm encountering is: django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...me_studentrest" ALTER COLUMN "id" TYPE uuid USING "id"::uuid -
Mocking instance methods in python unittest
I'm a software developer for several years but new to python. I'm writing a unit test (so no database connection present) that involves a model in Django that accesses another model referenced via a foreign key connection. I want to mock the method that accesses this connection and replace the result with a hard coded response, that is different for each instance though. Here's a minimal example: ### tests/test_MyTestCase.py from unittest import TestCase from djangoapi.models import * class MyTestCase(TestCase): def setUp(self): self.instance1 = MyModel() self.instance2 = MyModel() foreignKey1 = MySubModel() foreignKey1.my_value = 1 # Mock that self.instance1.submodel_set.all() returns [foreignKey1] foreignKey2 = MySubModel() foreignKey2.my_value = 2 # Mock that self.instance2.submodel_set.all() returns [foreignKey2] def testSomething(self): self.assertEqual(self.instance1.get_max_value(), 1) self.assertEqual(self.instance2.get_max_value(), 2) ### models.py from django.db import models class MyModel(models.Model): def get_max_value(self): value = 0 # the return value of self.submodel_set.all() is what I want to mock for model in self.submodel_set.all(): value = max(value, model.my_value) return value class Submodel(models.Model): my_model = models.ForeignKey(MyModel, null=True, on_delete=models.SET_NULL) my_value = models.IntegerField() I tried several combinations of the @patch decorator, Mock() and MagicMock() but could not get it to work. Thank you in advance! -
Unable to import CSV table in a model on PostgreSQL
I am doing a project on Django with database connected to postgreSQL. I did all the commands related to models as makemigrations and migrate so my tables appear on PgAdmin 4 correctly. The problema is for a particular table "Dashboard_país" with 2 columns (id and nombre) I am not able to import csv table, when with the other models importing csv I didnt have any problem. My model Dashboard_país looks like this: class País(models.Model): nombre = models.CharField(max_length=100) class Meta: verbose_name = "País" verbose_name_plural = "Países" def __str__(self): return self.nombre I receive the next error when import my csv: Running command: --command " "\copy public."Dashboard_país" (id, nombre) FROM 'C:/Users/auxer/Desktop/pais.csv' DELIMITER ';' CSV HEADER ENCODING 'UTF8';"" Start time: Thu Oct 19 2023 10:50:53 GMT+0200 (hora de verano de Europa central) \copy: error de procesamiento al final de la l�nea Processing error at the end of the line or something similar on english. I was searching on the internet and didnt find anyone with a similar error so I would be glad if anyone could help me Thanks. I tried import a simple CSV like this: Id;Nombre 1;John 2;Emma 3;Michael but it didnt work I also tried using query tool but commands doesnt … -
Azure Entra + Django SSL to many redirect
I try to connect MS Entra with Azure App. Everything works great on local version but production fail. Depending on the options SECURE_SSL_REDIRECT=False I got AADSTS50011: The redirect URl http:/myapp/auth/redirect specified in the request does not match the redirect URl's configured for the application. Of course in app on Azure I can't set http only https work. If SECURE_SSL_REDIRECT=True and Debug=False I got: To many redirect error. Cookies clean, different computer same error. Local test work with http and runserver In production I use gunicorn 443 port and docker. Cookies clean, different settings and computer. Some advice with gunicorn setting I think -
sock=backend at=error code=H18 desc="Server Request Interrupted"
Issue is, in my api view have some logic, and when a request hit to endpoint, there is two thing happening one is oauth2_provider validating token and other is logic execution for request, so when token validation failes it gatting 403 and it raising heroku\routing sock=backend at=error code=H18 desc="Server Request Interrupted" error and end user getting response as 503 instead of 403. I have implemented token validation system, where i have used django-oauth-toolkit package and deployed on heroku platform. Here, we are having separate Authorization and resource server, i have configured resource server as below mentioned. INSTALLED_APPS = ( ... 'oauth2_provider',) OAUTH2_PROVIDER = { ... 'RESOURCE_SERVER_INTROSPECTION_URL': 'https://example.org/o/introspect/', 'RESOURCE_SERVER_AUTH_TOKEN': '3yUqsWtwKYKHnfivFcJu', # OR this but not both: 'RESOURCE_SERVER_INTROSPECTION_CREDENTIALS': ('rs_client_id','rs_client_secret'), ...} i have used class based view ProtectedResourceView how to avoid this Heroku code=H18 503 getting into end user response and capture 403 and send as end user response if token validation fails with 403. -
Django server is not running suddenly
I had many working projects and suddenly when I tried to run the server using the: python manage.py runserver, I get the following output, and the server doesn't run: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). I have seen similar questions, but in their case the problem was related to connecting to the database, but in my case I'm using sqllite and even tried to start new django project and run the server and I have faced the same issue. -
Why do I get a no such table ERROR in Django with Django-crontab and not with manual execution?
Hello what is my problem? My problem is that when I run a crontab manually in Django with crontab run I can do database queries without problems but when the crontab runs alone I get the error no such table. I have already tried everything possible on my knowledge level and also googled but found no solution i hope you can help me. I marked the ERROR LINE IN CODE def fetch_data_from_iwps(): print_output_in_file("Start 1") print_output_in_file("Start 2") try: iwps = IWP.objects.filter(tracking_on_off=True, IP__isnull=False) # ERROR LINE print_output_in_file(iwps) """ for iwp in iwps: fetch_and_store_data(iwp) pass """ with concurrent.futures.ThreadPoolExecutor() as executor: print("multi") executor.map(fetch_and_store_data, iwps) pass pass except Exception as e: # Behandeln Sie etwaige Ausnahmen oder Fehler hier print("Error00") print_output_in_file(str(e)) pass sys.stdout = sys.__stdout__ print_output_in_file("Ende") pass i have already tried to check the imports and the settings also in the code i have used all possible error and tricks -
Invalid domain name error when trying to send email with django
Please help to resolve this issue: Facing following error when trying to send email in Django on Ubuntu: env/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 92, in open self.connection.starttls(context=self.ssl_context) File "/usr/lib/python3.10/smtplib.py", line 769, in starttls self.ehlo_or_helo_if_needed() File "/usr/lib/python3.10/smtplib.py", line 614, in ehlo_or_helo_if_needed raise SMTPHeloError(code, resp) smtplib.SMTPHeloError: (501, b'5.5.4 Invalid domain name') Email host is Hotmail Using standard settings for Django: EMAIL_HOST_USERNAME = 'x@hotmail.com' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' How to resolve this issue? Checked email settings for Hotmail Receiving email without "https/http" All characters in email address is in lowercase -
Error while installing psycopg2 on Windows - 'UnicodeDecodeError' during dependency resolution
I'm trying to install psycopg2 in a virtual environment for my Django project on Windows, but I'm encountering an error that I can't seem to resolve. The error I'm getting is as follows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 13: invalid continuation byte I've tried several solutions, but none of them have worked. I also saw a person who faced a similar issue on macOS and resolved it by installing OpenSSL with Homebrew and setting certain environment variables. Can you help me understand how to resolve this issue on Windows? Are there equivalents to the macOS environment export commands that I can use on Windows? Here's what I've already tried: [List the steps you've already taken, including the commands you've executed] [Provide any other relevant information about your environment, such as the Python version you're using] -
Dependencies errors using react-admin with ra-data-django-rest-framework
I created a new project using vite and installed react-admin. I have a backend in django so I want to use ra-data-django-rest-framework. But the issue is it's very old and when I try to install it's showing dependency error for react v16. Is there any alternative packages for this? I have REST api in django can I use some other data providers without any issues? -
Django stay on the same site after add item to cart and not append search url to another url
So i encounter 2 problem: First is i want to stay on the same site when add item to cart/favourite The idea is when the user search the product name, there will be list of products in the /search_result and i want user can add product from this list to a favourite db, and still stay in /search_result so they can add another product. Second is when i use search bar in /favourite the /search_url append to it become /favourite/search_url make in invalid My models: class Favourite(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) product = models.ManyToManyField(Product, through='FavouriteItem') class Meta: db_table = "scrape_favourite" class FavouriteItem(models.Model): favourite = models.ForeignKey(Favourite, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class Meta: db_table = "scrape_favouriteitem" My urls: urlpatterns = [ path("", views.search, name="search"), path("search_result", views.search_result, name ="search_result"), path("form/", views.form_view, name="form"), path("products/", views.products_view, name="products"), path("sign-up", views.sign_up, name="sign_up"), path('add-to-favourite/<int:product_id>/', views.add_to_favourite, name='add-to-favourite'), path('remove-from-favourite/<int:product_id>/', views.remove_from_favourite, name='remove-from-favourite'), path('favourite/', views.view_favourite, name='favourite'), ] My views: @login_required(login_url="/login") def add_to_favourite(request, product_id): product = Product.objects.get(pk=product_id) favourite = Favourite.objects.get_or_create(user=request.user)[0] favourite_item = FavouriteItem.objects.get_or_create(favourite=favourite, product=product)[0] # return redirect('/') @login_required(login_url='/login') def remove_from_favourite(request, product_id): product = Product.objects.get(pk=product_id) favourite = Favourite.objects.get(user=request.user) try: favourite_item = favourite.favouriteitem_set.get(product=product) favourite_item.delete() except FavouriteItem.DoesNotExist: pass # return redirect('/favourite') @login_required(login_url='/login') def view_favourite(request): try: newForm = ProductNameForm() favourite = request.user.favourite print(favourite) favourite_items = FavouriteItem.objects.filter(favourite=favourite) … -
How can I use an external CSS to override Bootstrap styles
I am using Bootstrap by directly linking to it over the internet without downloading it to my local files, and the page rendering has no major issues. However, I don't understand why some styles, like the .login-username, cannot be overridden, and they only work when written in the style tag. What might be the issue? main.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'tasks/main.css' %}"> <style> .login-username{ display: flex; } </style> </head> <body> <div class="center-column"> {% block content %} {% endblock content %} <div> </body> </html> It cannot be written in main.css. Writing it inside has no effect. main.css body{ background-color: #638CB8; } input{ width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; } input.title{ border:solid; } .center-column{ width:600px; margin: 20px auto; padding: 20px; background-color: #fff; border-radius: 3px; box-shadow: 6px 2px 30px 0px rgba(0,0,0,0.75); } .item-row{ padding: 20px; margin: 10px; font-size: 16px; background-color:#A1703E; border-radius: 3px; color: #fff; } .btn-warning{ background-color: #ffae19; border-color: #e59400; --bs-btn-color: #fff; --bs-btn-active-color: #fff; --bs-btn-hover-color: #fff; } #id_description{ width:100%; padding:20px; } input.id_complete{ width:100%; } /* login */ .login-username{ display: flex; } login.html {% … -
How to implement CSRF protection for user identification without login in DRF
I'm developing an app like anonymous bulletin board. The app is configured react and django rest framework. To identify user by cookie of uuid, I use custom middleware like this import uuid from django.contrib.sessions.middleware import SessionMiddleware from django.http.request import HttpRequest from django.http.response import HttpResponse class CustomMiddleware(SessionMiddleware): def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: user_id = request.COOKIES.get('user_id', None) if not user_id: max_age = 365 * 24 * 60 * 60 response.set_cookie( 'user_id', str(uuid.uuid4()), max_age=max_age, samesite='lax' ) return super().process_response(request, response) Then I googled how to protect the app from CSRF and couldn't find it. Please teach me the best way of it. regards. I tried to use session and csrf token, but I hovent any idea. -
How to change the value of inlines in an Django Admin form dynamically?
I'm trying to make the display of inline forms dynamic in Django according to the value of the "content_type" column, but I'm not succeeding. I've already tried overriding the get_inlines, get_inline_instance, and, finally, methods, as shown below: class XInline(nested_admin.NestedStackedInline): model = X fields = ["title", "some_field"] extra = 1 class YInline(nested_admin.NestedStackedInline): model = Y fields = ["title", "some_field"] extra = 1 class ZInline(nested_admin.NestedStackedInline): model = Z fields = ["title", "some_field"] extra = 1 class MyModelAdmin(nested_admin.NestedModelAdmin): list_display = ["id", "content_type"] def get_form(self, request, obj=None, **kwargs): if (obj): self.inlines = self.get_inlines() for inline in self.inlines: if obj.content_type.model == "x": self.inlines = [XInline] elif obj.content_type.model == "y": self.inlines = [YInline] elif obj.content_type.model == "z": self.inlines = [ZInline] return super(MyModelAdmin, self).get_form(request, obj, **kwargs) Ps.: that content_type is a ForeignKey of ContentType from from django.contrib.contenttypes.models -
When trying to deploy my Django app on AWS Elastic Beanstalk, I am getting the error "ModuleNotFoundError: No module named 'config.settings'"
I am attempting to deploy my Django app on AWS, but I keep getting errors like those mentioned in the title. I've tried changing the structure of my directory without luck. The below image shows my django.config file, along with the structure of my file directory: Django Directory Structure my django.config file looks like option_settings: aws:elasticbeanstalk:container:python: WSGIPath: lexgen.config.wsgi:application wsgi.py looks like import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') application = get_wsgi_application() I've tried changing my directory structure and moving references to config.settings, but that causes other parts of my program to break and create new error messages. Other answers I've read involve changing the django.config or wsgi.py files, in particular the WSGIPath in django.config, but I haven't been able to crack this just yet. If anyone has any insight into this problem, I'd really appreciate it. Happy to include any other information that may help answer this question. -
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'}),