Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i fix the Method not allowed (GET) error in django version 5 [duplicate]
i keep getting this error in logout.html in django everytime i go to it. Here is the code for the logout.html: <form method="post" action="{% url 'logout' %}"> {% csrf_token %} <button type="submit">logout</button></form> here is my views.py code: from django.shortcuts import render, redirect #from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate,login ,logout from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username= form.cleaned_data.get('username') messages.success(request, f'Account created successfully for {username}') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def logout(request): logout(request) return redirect('login') here is the urls.py code path('login/',auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), i expected the site to look like this: https://youtu.be/3aVqWaLjqS4?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&t=970 i am currently following the corey schafer youtube series as shared in the link -
Django settings not reflecting changes [closed]
I have a Django project running on an Ubuntu 22.04 server with Nginx and Gunicorn. After updating the project on my local server, I attempted to transfer it to my cloud server. Using FileZilla, I copied the new files to the server. However, the settings.py file did not update. I made changes to the settings.py file, and then rebooted Gunicorn and Nginx, but the changes did not take effect. I even tried deleting settings.py, but the server still did not respond to the changes. Cache is not enabled. Deleting all the .pyc files did not resolve the issue either. Does anyone know of a solution to this problem? -
How to add custom FileUploadHandler to request in ModelAdmin custom view Django 3.2
I need to add custom file upload handler in admin add and change view (using django 3.2). And getting an error. So far I created custom FileUploadHandler and trying to add to request in my ModelAdmin. Created class in my app\admin.py @admin.register(MyClass) class MyClassAdmin(ModelAdmin): def get_urls(self): urls = super().get_urls() custom_urls = [ url('^my_view/$', self.create_model_view, name='my_view'), ] return custom_urls + urls @csrf_exempt def create_model_view(self, request): request.upload_handlers = [CustomUploadHandler(request)] return super().changeform_view(request) And getting error You cannot set the upload handlers after the upload has been processed. What am i doing wrong? Where request is started processing? -
Django rest framework Status 200 but 'Failed to Load Response Data" On jwt token api
This is the token api of drf jwt. It is giving me 200 but in response it is saying me failed to load data I tried the code in locally it is running in the postman and also the url (https://v2.api.mytask.today/tsauth/api/token/) of server i gave it in the postman it is giving me access and refresh token but in browser it is giving me no response. -
Nginx + Django Static Files issue
I am having an issue with my project. I have everything working in my Django project, when the DEBUG=True in settings.py. But as soon as I change it to False, I get this issue when I go to my website (localhost): Error message with localhost when DEBUG=False Which probably means that either my static files are not correctly sent to my Nginx, or my Nginx web server is not correctly configured to receive/use my static files. Here is the docker-compose I am using: version: '3.8' services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app depends_on: - db environment: - DATABASE_URL=postgres://postgres:postgres@db:5432/postgres nginx: build: ./nginx ports: - "80:80" - "443:443" depends_on: - web restart: on-failure # Ensures NGINX retries if it fails to start the first time migrations: build: . command: sh -c "python manage.py makemigrations && python manage.py migrate" depends_on: - db volumes: postgres_data: Dockerfile for my Django project: # Use an official Python runtime as a parent image FROM python:3.9-slim # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY requirements.txt /app/ RUN pip … -
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 …