Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF cookie doesn't show up in browser cookies after made a request from React to Django and @ensure_csrf_cookie
The question is clear. I made a request from React side to http://localhost:8000/csrf_cookie and my Set_CSRF_CookieView executed in Django side. The response is OK and I'm receiving csrftoken in Response Headers but It won't set on my browser cookies. React port: http://localhost:5173 Django port: http://localhost:8000 You can see csrftoken inside Set-Cookie section of Response Headers: You can see csrftoken cookie is not set on browser cookies My codes => views.py: @method_decorator(ensure_csrf_cookie, name='dispatch') class Set_CSRF_CookieView(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({'success': 'CSRF cookie set.'}) settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'App.apps.AppConfig' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Sessions SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_NAME = "TDSession" SESSION_COOKIE_HTTPONLY = True # SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 60 * 60 * 24 * 3 CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'Lax' # DRF REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication' ] } CORS_ORIGIN_ALLOW_ALL = True CSRFToken.jsx import React, { useState, useEffect} from 'react'; import axios from 'axios'; import { useDispatch, useSelector } from 'react-redux'; … -
django get() triggers FOUR queries
During deep debuging i found that simple .get triggers FOUR queries: kwargs['context']['user'] = models.Person.objects.get( pk=16879 ) And postgresql.log prints this: 2024-05-08 10:21:07.913 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 2024-05-08 10:21:07.927 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 2024-05-08 10:21:07.937 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 2024-05-08 10:21:07.946 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 I thought, that this code is in some loop, but I did this: # raise ValueError('before') kwargs['context']['user'] = models.Person.objects.get( pk=16879 ) raise ValueError('after') first I run this with raise before, and no queries at all, than … -
Cannot get django-admin css file in "Django + nginx + docker"
I could not serve the Django-admin's static files... I think.. It can't not recognize the reverse-proxy path. the location /static/admin/ Literally, The Django static folder is in upstream django server. There is nginx.conf and the inside docker container with django. Please tell me the solution... nginx # nginx upstream react { server 10.180.225.1:3000; } upstream django { server 10.180.226.1:8000; keepalive 100; } server { listen 80; include mime.types; location /static/admin/ { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /admin { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; add_header Test "This is for proxy pass."; } location /api { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_read_timeout 3600s; proxy_connect_timeout 3600s; } location / { proxy_pass http://react; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } } docker exec -it back-web /bin/bash ls... Django Admin page -
Cannot resolved keyword 'date_created' into field
I have a problem with runserver on PowerShell. entries_detail.html: <article> <h2>{{ entry.date_created|date:'Y-m-d H:i' }}</h2> <h3>{{ entry.title }}</h3> <p>{{ entry.content }}</p> </article> entries_list.html: {% for entry in entry_list %} <article> <h2 class="{{ entry.date_created|date:'l' }}"> {{ entry.date_created|date:'Y-m-d H:i' }} </h2> <h3> <a href="{% url 'entry-detail' entry.id %}"> {{ entry.title }} </a> </h3> </article> {% endfor %} views.py: from django.views.generic import ( DetailView, ListView, ) from django.db import models from .models import Entry --- class EntryListView(ListView): model = Entry queryset = Entry.objects.all().order_by("-date_created") class EntryDetailView(DetailView): model = Entry I tried to run python manage.py runserver on PowerShell and I got the result: django.core.exceptions.FieldError: Cannot resolve keyword 'date_created' into field. Choices are: content, data_created, id, title -
how to connect to broker Websocket in django
I am building an algotrading platform, i have access to broker apis and websockets, but i dont know how to connect to broker websocket and consume the data on realtime basis in django I have setup channels: #consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() self.external_socket = websocket.WebSocketApp( "wss://api.shoonya.com/NorenWSTP/", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, ) self.send(text_data=json.dumps({ 'type':'connection_established', 'message':'You are now connected!', })) self.external_socket.run_forever() #routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi()) ] #asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import authengine.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'atkmain.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( authengine.routing.websocket_urlpatterns ) ) }) -
Why is django debug toolbar causing a 'ValueError at ... Another profiling tool is already active' error when Htmx ajax fires?
I had django-debug-toolbar working fine in my application until I added htmx. Now I'm getting Another profiling tool is already active error. The page loads then htmx fires on load to add more content. Below is the offending line <div id="group-list" hx-get="{% url "my-rental-property-groups" rental_property.id %}" hx-trigger="load"></div> If I change the change the hx-trigger attribute to hx-trigger="load delay:5s" to add a delay of 5 seconds, then the error goes away but that's not a solution. A smaller delay still throws the same error. If I add "SHOW_TOOLBAR_CALLBACK": lambda request: False, to DEBUG_TOOLBAR_CONFIG section below, the page renders fine but the Debug Toolbar is disabled DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": lambda request: False, #THIS LINE DISABLES DEBUG TOOLBAR WIHOUT SETTING DEBUG TO FALSE "SHOW_TEMPLATE_CONTEXT": True, "ROOT_TAG_EXTRA_ATTRS": "hx-preserve", # https://django-debug-toolbar.readthedocs.io/en/latest/tips.html#working-with-htmx-and-turbo } I'm looking for a solution that will allow me to keep Htmx and Django Debug Toolbar working together. -
Docker-compose: Creating same container for different projects
I'm facing an issue with my Django projects that have a similar structure. Each project has a backend folder containing a docker-compose.yml and Dockerfile. The structure is as follows: project1/backend/docker-compose.yml project2.backend/docker-compose.yml The problem arises when I switch between projects and run docker-compose up. It seems that the container named backend is reusing services from the previous project instead of creating a new container. Here's an example of the docker-compose.yml for each project: Project 1: version: '3.9' services: redis: image: redis:latest ports: - "6379:6379" postgres: image: postgres:12 container_name: postgres environment: POSTGRES_PASSWORD: project_name POSTGRES_DB: project_name env_file: - .env ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ celery: build: context: . dockerfile: Dockerfile command: celery -A project_name worker -l info volumes: - .:/opt/webapp depends_on: - redis - postgres celery-beat: build: context: . dockerfile: Dockerfile command: celery -A project_name beat -l info volumes: - .:/opt/webapp depends_on: - redis - postgres volumes: postgres_data: Project 2: version: "3.9" services: web: build: context: . args: SECRET_KEY: ${SECRET_KEY} env_file: .env volumes: - ./:/opt/webapp ports: - "8000:8000" # Added Command for hot reloading in dev server command: > sh -c "python3 manage.py runserver 0.0.0.0:8000" postgres: env_file: .env environment: POSTGRES_PASSWORD: project_name volumes: - postgres-data:/var/lib/postgresql/data ports: - "5432:5432" redis: env_file: .env ports: - … -
How to use Django AutocompleteFilter thtough 2 relations?
i have Django models hierarchy class Workspace(Model): title = CharField() class User(Model): workspace = ForeignKey(to=Workspace) class Chat(Model): user = ForeignKey(to=User) In Django admin at Chats page i want to filter them by workspace, but there are many workspaces, so i need select2 At Users page i use AutocompleteFilter (django-admin-autocomplete-filter package) But it do not work at Chats page. Questions: Is it possible to use AutocompleteFilter in this case? How? Are there any other solution to make Autocomplete dropdown filters? -
How to connect django 5.0.3 to SQL Server database
I have been trying to connect django with SQL server but there are errors occurring continuously no matter what I try. For example DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'xxxxx', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I get this error: File "C:\Users\Admin\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\sql\where.py", line 180, in as_sql raise FullResultSet django.core.exceptions.FullResultSet When I change Engine to "mssql" I get this error: django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
DJANGO ImportError: cannot import name 'url' from 'django.conf.urls' version 5.0.3
I'm following this DJANGO Rest Framework tutorial: https://www.youtube.com/watch?v=eA4H3p95hbM&list=PLmDLs7JbXWNjr5vyJhfGu69sowgIUl8z5&index=4 After modifying in 'urls.py', then type "python manage.py migrate" I get this error: from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (F:\Learning HTML and CSS\DJANGO_DAVE GRAYE.venv\Lib\site-packages\django\conf\urls_init_.py) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) I have search solution for this error. But they are working on DJANGO version 4.0 above and my current version is 5.0. I try follow their solution but it seems not working in my case -
his error originates from a subprocess, and is likely not a problem with pip
pip install validate email Collecting validate Using cached validate-1.0.1.tar.gz (32 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [23 lines of output] Traceback (most recent call last): File "C:\Users\beras.virtualenvs\django-GatewayMonitoring-website-_fBZbT0M\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 353, in main() File "C:\Users\beras.virtualenvs\django-GatewayMonitoring-website-_fBZbT0M\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\beras.virtualenvs\django-GatewayMonitoring-website-_fBZbT0M\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 295, in _get_build_requires self.run_setup() File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 487, in run_setup super().run_setup(setup_script=setup_script) File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 311, in run_setup exec(code, locals()) File "", line 13, in File "C:\Users\beras\AppData\Local\Temp\pip-install-6bmuq9nw\validate_74389ea5db364065a48c1b8f2d9e1ca1\configobj.py", line 1632 except Exception, e: ^^^^^^^^^^^^ SyntaxError: multiple exception types must be parenthesized [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I'm currently working in a django project, and tried to install "validate email". I'm unable to install it. -
Django Annotation: Convert time difference to whole number or decimal
I am trying to sum the hours user spent per day. I wanted to convert this into whole number or decimal (e.g. 2, 6.5) hrs, to easily plot this to my chart. But the result of below code is in this format HH:mm:ss. Any one can help me with this? day = Clocking.objects.filter(clockout__isnull=False, user=nid).annotate(date=TruncDate('clockin')) .values('date').annotate(total=Sum(F('clockout') - F('clockin'))).values('total') Here is my models.py class Clocking(models.Model): user= models.ForeignKey('User', models.DO_NOTHING) clockin = models.DateTimeField() clockout = models.DateTimeField(null=True) -
Use the Django ORM to do a left outer join between unrelated models?
Suppose I have two models: class One(models.Model): name = models.CharField(max_length=300, unique=True) class Two(models.Model): name = models.CharField(max_length=300, unique=True) They are not related by a foreign key, and there are reasons to leave it that way in this project. I want to know the One instances with a name that is not in Two. Here is the SQL to get that: select app_one.name from app_one left join app_two on app_one.name = app_two.name where app_two.name is null group by 1; Is it possible to get that through the ORM, or do I just have to write a query? -
How to deliver Django+Postgresql projects to clients?
I have been working on a project where my client wants me to load some csv files data into the database and he wants me to use Postgresql. The problem is that sqlite has a physical database stored in django directory which can be delivered along with the project but postgres doesn't work this way. What can I do so that all my relational databases remain intact and I can deliver them to the client's machine? I saw some search results about dumpdata and load data commands but I was wondering if there is any better way to do this? -
How do I expose information from Django model to the forms/views(?)/html(?) to be able to see all information built-in the model
I am trying to add more information to a form dropdown built using Django forms. A basic explanation of the program is: The user logs in The user can create 'decks' that are to be displayed on the 'game_tracking' page The user goes to the 'game_tracking' page, and the first dropdown loads all of the names of decks that the user created as well as the additional info from the model 'Deck' of if it is/isn't a cEDH deck. I am unsure of how to expose whether the deck's information of is_cedh, in addition to the name, in the dropdown This is what it currently shows when I expand the dropdown This, ideally, is what I am attempting to do. Thanks in advance for taking the time to read/answer. I have been working on this for longer than I would like to admit... This is my models.py file. from django.db import models from django.contrib.auth.models import User class Profile(models.Model): profile_pic = models.ImageField(null=True, blank=True, default='Default.png', upload_to='images/') user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.user) class Deck(models.Model): deck = models.CharField(max_length=150) is_cedh = models.BooleanField(default=False) user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.deck) class Game(models.Model): NUM_PLAYERS_CHOICE = [ (2, 2), (3, … -
Users that will be using a django form and posting data
I have created a django web app with CRUD functionality, i want to be able to see the users (With their names) that have posted on the form and see a full list of the data they post along with their names next to the data. I don't know how to go about coding that. My Model code is: from django.db import models from django.contrib.auth.models import User # Create your models here. class Agent(models.Model): Role = [ ('Manager','Manager'), ('Agent','Agent'), ] QA_Agent = models.OneToOneField(User, on_delete=models.CASCADE, choices=Role) def __str__(self): return self.QA_Agent.username QA_Outcome = [ ('FALSE','FALSE'), ('TRUE','TRUE'), ] KPA_Outcome = [ ('Product','Product'), ('Pass','Pass'), ('Compliance','Compliance'), ('Data Capturing','Data Capturing'), ('TCF','TCF'), ] HIV_Test = [ ('YES','YES'), ('NO','NO'), ] AVS = [ ('PASS', 'PASS'), ('FAIL', 'FAIL'), ('UNVERIFIED', 'UNVERIFIED'), ] StartDate = [ ('1st January','1st January'), ('1st February','1st February'), ('1st March','1st March'), ('1st April','1st April'), ('1st May','1st May'), ('1st June','1st June'), ('1st July','1st July'), ('1st August','1st August'), ('1st September','1st September'), ('1st October','1st October'), ('1st November','1st November'), ('1st December','1st December'), ] # Create your models here. class QA_Models(models.Model): Policy_Number = models.CharField(max_length=12) Case_Number = models.CharField(max_length=7) AVS_Check = models.CharField(choices=AVS, max_length=12) Caller_ID = models.CharField(max_length=50) Call_duration = models.CharField(max_length=10) Start_date = models.CharField(choices=StartDate, max_length=20) Premium = models.DecimalField(max_digits=6, decimal_places=2) Debit_date = models.CharField(max_length=10) Cover_amount = models.CharField(max_length=10) QA_Correct … -
i have some errors while im trying to have a special number for each page in Django
I used int:observatory_id to provide a special number for each pages without any special typos and mistakes and i have this error Reverse for 'observatory' with arguments '('',)' not found. 1 pattern(s) tried: ['observatorys/(?P<observatory_id>[0-9]+)\Z'] here is my code : urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.observatorys, name="observatorys"), path('<int:observatory_id>', views.observatory, name="observatory"), ] views.py : from django.shortcuts import render from .models import Observatory def observatorys(request): observatorys = Observatory.objects.all() context = { ' observatorys': observatorys } return render(request, 'observatory/observatorys.html', context) def observatory(request, observatory_id): context = { 'id': observatory_id } return render(request, 'observatory/observatory.html', context)``` template.html : <!-- Start Province --> <a class="map-link" xlink:href="#khorasan-r" href="{% url 'observatory' observatory.id %}"> <svg class="map-province khorasan-r"> <use xlink:href="../../static/svg/main-map.svg#khorasan-r"></use> </svg> </a> please help me asap. -
Django - Removing subdomains from my multitenancy app
I have a working multitenancy app in Django with isolated databases that currently uses a subdomain for each tenant and threading. The subdomain prefix is used to make a connection to the corresponding database, so: client1.mysite.com access the database client1 client2.mysite.com access the database client2 And so on. This is the current code I have: middleware: import threading from app.utils import tenant_db_from_the_request Thread_Local = threading.local() class AppMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): db = tenant_db_from_the_request(request) setattr(Thread_Local, 'DB', db) response = self.get_response(request) return response def get_current_db_name(): return getattr(Thread_Local, 'DB', None) utils: def hostname_from_the_request(request): return request.get_host().split(':')[0].lower() def tenant_db_from_the_request(request): hostname = hostname_from_the_request(request) tenants_map = get_tenants_map() return tenants_map.get(hostname) def get_tenants_map(): return dict(Tenants.objects.values_list('subdomain', 'database',)) routers: class AppRouter: def db_for_read(self, model, **hints): return get_current_db_name() def db_for_write(self, model, **hints): return get_current_db_name() def allow_relation(self, *args, **kwargs): return True def allow_syncdb(self, *args, **kwargs): return None def allow_migrate(self, *args, **kwargs): return None Using subdomains is not exactly ideal, so I'm trying to switch the subdomain prefix to a suffix that will be added to the username of each tenant. With that, every tenant will access the same URL: mysite.com And the suffix will be added to the username like that: user@client1 access the database client1 user@client2 … -
how to set up DJANGO_SETTINGS_MODULE with absolute path of the settings.py file
I need to write some scripts for django and trying to set up the DJANGO_SETTINGS_MODULE environment variable at the beginning of each script. The scripts, manage.py and myproject directory are in the same parent directory. Additionally, settings.py file is in myproject directory. Therefore, following code works correctly #test_script_header.py import os os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" import django django.setup() But following code doesn't work #test_script_header.py import os os.environ["DJANGO_SETTINGS_MODULE"] = "/home/<username>/workspace/djangoapp/src/myproject/settings.py" import django django.setup() I get the error ModuleNotFoundError: No module named '/home/<username>/workspace/djangoapp/src/myproject/settings.py' Here is the complete error message Traceback (most recent call last): File "/home/<username>/workspace/djangoapp/src/test_script_header.py", line 22, in <module> django.setup() File "/usr/lib/python3/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named '/home/<username>/workspace/djangoapp/src/myproject/settings' However, I want to eventually move … -
How to make user in Django choose the workshop he added to make a service record for his own car?
im struggling with same problem for 3 days now, im trying to make my finish project which is some kind of online servicebook for cars we own, i have models vehicle, workshop, filter, servicerecord and i cant add servicerecord to the car i have added is there anyone who could help me? Here comes a little bit of code i have problems with from forms.py and views.py: class ServiceRecordCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): `super().__init__(*args, **kwargs) all_workshops = Workshop.objects.exclude(name="Other Workshop") workshop_choices = [(workshop.id, workshop.name) for workshop in all_workshops] workshop_choices.insert(0, (0, 'Other Workshop')) self.fields['workshop'].widget = forms.Select(choices=workshop_choices) self.fields['workshop'].choices = workshop_choices all_filters = Filter.objects.all() filter_choices = [(filter.id, filter.name) for filter in all_filters] self.fields['filters_changed'].widget = forms.CheckboxSelectMultiple() self.fields['filters_changed'].choices = filter_choices def clean_workshop(self): workshop_id = self.cleaned_data.get('workshop') if workshop_id == 0: # Obsługa przypadku "Other Workshop" workshop = Workshop.objects.filter(name="Other Workshop").first() if not workshop: raise forms.ValidationError("Other Workshop is not available.") else: workshop = Workshop.objects.get(id=workshop_id) return workshop class Meta: model = ServiceRecord fields = ['workshop', 'date', 'mileage_at_service', 'filters_changed'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } class ServiceRecordCreateView(LoginRequiredMixin, CreateView): model = ServiceRecord form_class = ServiceRecordCreateForm template_name = 'create_service_record.html' def get_success_url(self): vehicle_id = self.kwargs['vehicle_id'] return reverse_lazy('service_record_list', kwargs={'vehicle_id': vehicle_id}) def form_valid(self, form): service_record = form.save(commit=False) service_record.vehicle_id = self.kwargs['vehicle_id'] service_record.save() form.save_m2m() return redirect(self.get_success_url()) i … -
serve django staticfiles with nginx inside docker
I have problem with staticfiles for django admin panel. for rest framework frontend panel the files are served without problem settings.py STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_ROOT.mkdir(exist_ok=True) Dockerfile: FROM python:3.10-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 RUN python manage.py collectstatic --noinput docker-compose: version: '3.8' services: web: build: . command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app # - static_volume:/usr/share/nginx/html/static ports: - "8000:8000" nginx: image: nginx:1.19-alpine ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/conf.d:/etc/nginx/conf.d - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot # - static_volume:/usr/share/nginx/html/static # Ensure this matches the alias in nginx.conf - static_volume:/app/staticfiles volumes: static_volume: nginx/conf.d.default.conf server { listen 80; server_name localhost; location /static/ { alias /usr/share/nginx/html/static; # Ensure this matches the volume mapping in docker-compose.yml autoindex on; # Optionally enable to troubleshoot file listing } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } It's my first time building app using django, gunicorn, nginx my config files are from chatgpt and tutorials. if i'm doing some mistake and someone will point it it'd great -
How to add results to a test in Django quiz app?
I'm just learning Django and trying to create a test. I watched the video on YouTube, but I didn't quite understand how to add the test results to the page. I created the test and in the SQLite database, I can create categories, questions, answers, and answer scores. How can I withdraw the points for the answers after sending the answers.I would like the answers to appear on the quiz_detail page. In the form of correct/incorrect (under each question) or in the form of a "Total score". Quiz_detail.html {% extends "base.html" %} {%block content%} <div class="parent-div"> <div class="centered-div"> <h3 class="title">{{quiz.title}}</h3> <form method="post" id="quizform" action="{% url 'quiz_submit' quiz.id %}"> {%csrf_token%} {%for question in questions%} <h2> {{question.text}}</h2> <h2 class="white-container">{{question}}</h2> <h3 class="grey-container"> {%for choice in question.choices.all%} <input type="radio" id="choice_{{choice.id}}" name="question_{{question.id}}" value="{{choice.id}}" /> <label for="choice_{{choice.id}}">{{choice.text}}</label> <br /> {%endfor%} {%endfor%} </h3> <button type="submit">Submit quiz</button> </form> {% block title %}Result{% endblock %} </div> </div> {%endblock%} models.py class Question(models.Model): text = models.CharField(max_length=225) quiz = models.ForeignKey(Quiz, related_name="questions", on_delete = models.CASCADE) def __str__(self) -> str: return self.text class Choice(models.Model): text = models.CharField(max_length=225) question = models.ForeignKey(Question, related_name="choices", on_delete = models.CASCADE) score = models.FloatField(default=0) is_correct = models.BooleanField('Correct', default=False) comment = models.CharField('comment', default=False, max_length=225) def __str__(self) -> str: return self.text class UserResponse(models.Model): … -
Graphene django. Get error: String cannot represent value '(value, )' after mutation attempt
I'm new to graphene library and make updating mutation as was in documentation. Also I looked at this video about CRUD : https://youtu.be/C-EfYVXShLE?si=uksgjJEuavU1k9GW I thought, that problem was in mutate arguments, I tried to make it with kwargs, but result was the same. Unfortunatly, most guides was using django-rest to write crud, but I would like to make it without others dependecies. Here's the code: class UpdateAddress(graphene.Mutation): address = graphene.Field(AddressType) class Arguments: address_id = graphene.ID(required=True) index = graphene.String() street = graphene.String() house = graphene.String() flat = graphene.String() locality = graphene.Int() @classmethod def mutate(cls, root, info, address_id, index=None, street=None, house=None, flat=None, locality=None): address = Address.objects.get(pk=address_id) try: entry = Locality.objects.get(pk=locality) except Locality.DoesNotExist: entry = None address.index=index, address.street=street, address.house=house, address.flat=flat, address.locality=entry address.save() return UpdateAddress(address=address) When i try to update some field with this query: mutation { updateAddress( addressId: "1", index: "41204" street: "Shevchenko", house: "1", flat: "15", locality: 1 ) { address{ id, street, index, house, flat, locality{ id } } } } I recieve errors: "errors": [ { "message": "String cannot represent value: ('41204',)", "locations": [ { "line": 12, "column": 7 } ], "path": [ "updateAddress", "address", "index" ] } ], Somehow it sets all string values to a tuple and I … -
not able to connect to external mysql db in django
i am again and again failing to connect to external mysql db on phpmyadmin db as my django keeps connnecting to its localhost database i have tried many things but not getting success can you guys help me please #db conf in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', "USER": "user", "PASSWORD": "password", "host": 'host_ip', 'PORT': 3306, } } i have already installed packages like mysql and mysqlclient but still not able to connect to external db, and when i do migration i get errors like localhost target machine actively refused connection -
why my content is not showing between blockcontent and endblock in django?
i have build an other app in my django project and have a template in my templates folder and i am including the base.html from my other app but the problem is in when i want to write html in my block content tags its showing it below the footer not in between the navbar and the footer {% include 'webapp/base.html' %} {% load static %} {% block content %} Patient Info {% endblock %} the screenshot is below why i am getting this below my footer its working perfect in my firstapp in project all the other things like statics are loading but when i write anything in block tags its showing it in below the footer of my base.html this is happening only in my patients app not in webapp in webapp i also extending my base.html and its showing the block content in the block contents tag of base.html but in patients app its not showing inbetween the blockcontents