Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django sees old migrations but everything was deleted
I cleared all my database, even created new with different name, deleted all migrations and migrations folder in every app of my django project, cleared all images, containers, volumes and builds in my Docker. But when I am running python manage.py showmigrations it shows me my old migrations, but I have no idea where does it finds them, because I deleted everything I could. and when I am running python manage.py makemigrations it returns me message "No changes detected" I even changed database name to new one. I deleted everything and just wanted to start from zero, but somehow it finds old migrations that doesn't even exist. enter image description here -
Can I make a dj-rest-auth login screen that uses a different database for login details?
I want to make a login screen for my Django Rest framework. I want to create a login page that's based on my database and not the default credentials of dj-rest-auth. Is it possible to do? Or should I use something else? I looked for solutions to this and only found ways to customize my the login details with the default django auth database. -
Django Rest Framework - Cross Origin Resquest got blocked
I'm developing an API using Django Rest Framework. I'm trying to list or create an "Article" object, but when i'm trying to access the console gives me this error: I host my frontend at http://localhost:3000 and sending request to 127.0.0.1:8000 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/articles/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. With this in setting.py, I got the above error CORS_ALLOWED_ORIGINs = [ "http://localhost:3000", ] but if using this code then it runs smoothly CORS_ORIGIN_ALLOW_ALL = True This is my GET request useEffect(() => { fetch("http://127.0.0.1:8000/api/articles/", { 'method': "GET", headers: { 'Content-Type': 'application/json', 'Authorization': 'Token 746a97c3f72a5fc388762c5732e2c8340fc75ba9', } }) .then(res => res.json()) .then((data) => setArticles(data)) .catch((error) => console.log(error)) }, []); Other configurations in setting.py seem to be set up correctly. -
Stream an entire folder using Django without reading everything to memory
The premise is similar to this question. But the accepted answer not only requires every file to be in memory to work. The answer does provide an example of iterator usage but that doesn't work with open(file, 'rb').read(chunk_size). More importantly that solution doesn't actually download folder. It only group multiple files togather. -
with Django , When I use connection pool , eoor(PoolTimeout) occurs. why?
When I use connection pool, yhere is no problem when starting it for the first time run, but, After a while, an error will start occurring. Traceback (most recent call last): File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/utils.py", line 1786, in runner return sentry_patched_function(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/integrations/django/__init__.py", line 692, in connect return real_connect(self) ^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 348, in get_new_connection connection = self.pool.getconn() ^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/psycopg_pool/pool.py", line 202, in getconn raise PoolTimeout( psycopg_pool.PoolTimeout: couldn't get a connection after 30.00 sec The above exception was the direct cause of the following exception: Traceback (most recent call last): File "repli/web/django/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/integrations/django/views.py", line 90, in sentry_wrapped_callback return callback(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/user/.pyenv/versions/3.11.2/lib/python3.11/contextlib.py", line 80, in inner with self._recreate_cm(): File "web/django/venv/lib/python3.11/site-packages/django/db/transaction.py", line 198, in __enter__ if not connection.get_autocommit(): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 454, in get_autocommit self.ensure_connection() File "web/django/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line … -
Django Testing in PyCharm. manage
I have a simple django project that I'm making in pycharm. The directory structure is the following: zelda_botw_cooking_simulator |-- cooking_simulator_project |---- manage.py |---- botw_cooking_simulator # django app |------ init.py |------ logic.py |------ tests.py |------ all_ingredients.py |------ other standard django app files |---- cooking_simulator_project # django project When I run python manage.py test in the PyCharm terminal, everything works great. When I click the little triangle icon in PyCharm next to a test to run that test, however, I get an error saying: File ".../zelda_botw_cooking_simulator/cooking_simulator_proj/botw_cooking_simulator/tests.py", line 5, in <module> from .all_ingredients import all_ingredients ImportError: attempted relative import with no known parent package How can I fix this? I have tried configuring run environments and test environments in PyCharm for 30 minutes now and I'm not getting it. The questions/answers here and here are close, but there's not quite enough detail for me to fix it. Exactly what do I put in each field in each window? What's the 'target', the 'working directory', do I need an environment variable? What goes in the settings part and what goes in the configuration? ChatGPT recommended a bunch of stuff that didn't work. Thank you! -
Under what circumstances will django's bulk_update generate case when?
When running the following program, I found that case when SQL was finally executed. In which part of the Django source code is this processing logic implemented? How to optimize it? Thanks Django ORM AccountInfo.objects.bulk_update(update_list, ['account_name', 'account_status', 'account_type']) executed SQL UPDATE account_info SET account_name = CASE WHEN (account_info.id = 814245) THEN 'Beeeesos' WHEN (account_info.id = 814248) THEN 'Apple223' ... -
Django SelectDateWidget default values for month and year only
I use the SelectDateWidget in my form and want to give default values for year and month, but show the empty_label (----) on day. I either get all three fields to be empty_label, or all fields showing the default date (timezone.now()). -
How to edit lines of bar chart in apache superset based on threshold
***I am unable to customise colour of bar char in Apache super-set dashboard. The goal is if count/sum/avg is greater then 100 the colour should be blue of the line, elif greate then 1200 the colour should be red of the line and so on. I have tried to alter yaml files but failed. Here is my yaml file. I am currently trying to modify vaccine dashboard bar chart (vaccine candidate per phase). The colour for count should be dynamic. Any suggestion? What should be yaml file, SQL query? or any changes needed in react components???*** .... description: '' chartsInScope: - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 66 tabsInScope: - TAB-BCIJF4NvgQ id: NATIVE_FILTER-EWNH3M70z controlValues: enableEmptyFilter: false defaultToFirstItem: false multiSelect: true searchAllOptions: false inverseSelection: false name: Clinical Stage filterType: filter_select targets: column: name: clinical_stage datasetUuid: 974b7a1c-22ea-49cb-9214-97b7dbd511e0 defaultDataMask: extraFormData: {} filterState: {} ownState: {} cascadeParentIds: [] scope: rootPath: ROOT_ID excluded: [] type: NATIVE_FILTER description: '' chartsInScope: 9 10 11 12 13 14 15 66 tabsInScope: TAB-BCIJF4NvgQ color_scheme: supersetColors label_colors: "0": "#D3B3DA" "1": "#9EE5E5" Pre-clinical: "#1FA8C9" Phase II or Combined I/II: "#454E7C" Phase I: "#5AC189" Phase III: "#FF7F44" Authorized: "#666666" root: "#1FA8C9" Protein subunit: "#454E7C" … -
Django storages + boto3 not working. Keeping static files local while uploading media files to S3
I'm trying to setup a django project in such a way that static files are kept in the filesystem and media files are uploaded to an amazon s3 bucket. The django storages library had an update for django>4.2. This used to be easy, now, its not working with the new settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'django.core.files.storage.FileSystemStorage' # Check if running in a production environment STORAGES = { 'default': { 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage', 'OPTIONS': { 'bucket_name': os.getenv('AWS_STORAGE_BUCKET_NAME'), 'region_name': os.getenv('AWS_S3_REGION_NAME', 'us-east-1'), 'default_acl': 'public-read', 'file_overwrite': False, 'custom_domain': f'{os.getenv("AWS_STORAGE_BUCKET_NAME")}.s3.{os.getenv("AWS_S3_REGION_NAME", "us-east-1")}.amazonaws.com', }, }, 'staticfiles': { 'BACKEND': 'django.core.files.storage.FileSystemStorage', 'OPTIONS': { 'location': STATIC_ROOT, }, } } # django-storages configuration for media files DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = f'https://{os.getenv("AWS_STORAGE_BUCKET_NAME")}.s3.{os.getenv("AWS_S3_REGION_NAME", "us-east-1")}.amazonaws.com/media/' When accessing the site from the server, the static files still point to the s3 bucket, for example: us-east-1.amazonaws.com/media/admin/css/dark_mode.css That is the basic css for the django admin. But why is it looking for the file in /media/? -
TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard' on Mac
I was developing my fastapi project in my windows PC and everything was working fine there, but I recently got a new macbook and installed the lastest python 3.13 version and everything is just giving error When I try to run my fastapi server, its giving this error :- (venv) venvlisa@Lisas-MacBook-Air src % uvicorn main:app --host 0.0.0.0 --port 8000 --reload INFO: Will watch for changes in these directories: ['/Users/lisa/Documents/Projects/phia-backend-python/src'] INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: Started reloader process [67473] using WatchFiles Process SpawnProcess-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap self.run() ~~~~~~~~^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/_subprocess.py", line 76, in subprocess_started target(sockets=sockets) ~~~~~~^^^^^^^^^^^^^^^^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/server.py", line 61, in run return asyncio.run(self.serve(sockets=sockets)) ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/runners.py", line 194, in run return runner.run(main) ~~~~~~~~~~^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/runners.py", line 118, in run return self._loop.run_until_complete(task) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/base_events.py", line 721, in run_until_complete return future.result() ~~~~~~~~~~~~~^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/server.py", line 68, in serve config.load() ~~~~~~~~~~~^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/config.py", line 473, in load self.loaded_app = import_from_string(self.app) ~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "/Users/lisa/Documents/Projects/phia-backend-python/venv/lib/python3.13/site-packages/uvicorn/importer.py", line 21, in import_from_string module = importlib.import_module(module_str) File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/importlib/__init__.py", line 88, in import_module return _bootstrap._gcd_import(name[level:], package, level) ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen … -
Dokku Procfile "release: python manage.py migrate" results in a NodeNotFoundError "Migration XYZ dependencies reference nonexistent parent node"
When i push to the dokku test environment, i get the following error when the Procfile is being used: -----> Releasing aha-website-test... -----> Checking for predeploy task No predeploy task found, skipping -----> Checking for release task Executing release task from Procfile in ephemeral container: python manage.py migrate =====> Start of aha-website-test release task (825335cfe) output remote: ! Traceback (most recent call last): remote: ! File "/app/manage.py", line 10, in <module> remote: ! execute_from_command_line(sys.argv) remote: ! ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line remote: ! utility.execute() remote: ! ~~~~~~~~~~~~~~~^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 436, in execute remote: ! self.fetch_command(subcommand).run_from_argv(self.argv) remote: ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 413, in run_from_argv remote: ! self.execute(*args, **cmd_options) remote: ! ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 459, in execute remote: ! output = self.handle(*args, **options) remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 107, in wrapper remote: ! res = handle_func(*args, **kwargs) remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/commands/migrate.py", line 118, in handle remote: ! executor = MigrationExecutor(connection, self.migration_progress_callback) remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/executor.py", line 18, in __init__ remote: ! self.loader = MigrationLoader(self.connection) remote: ! ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/loader.py", line 58, in __init__ remote: ! self.build_graph() remote: ! ~~~~~~~~~~~~~~~~^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/loader.py", line 276, in build_graph … -
Git pull fails with "RPC failed; curl 92 HTTP/2 stream 7 was not closed cleanly: CANCEL (err 8)"
I'm having trouble running git pull from my repository. The command fails with the following error messages: remote: Enumerating objects: 42, done. remote: Counting objects: 100% (34/34), done. remote: Compressing objects: 100% (11/11), done. error: RPC failed; curl 92 HTTP/2 stream 7 was not closed cleanly: CANCEL (err 8) error: 4136 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: unpack-objects failed It seems like the operation is failing during the transfer. I've tried running the command multiple times, but I keep getting the same error. Increased the Git buffer size using the following command, but it didn’t resolve the issue: git config --global http.postBuffer 524288000 Checked my internet connection, which seems stable and works fine with other services. -
Selenium(chrome driver) and Gunicorn problem workers close immediately after starting with daemon
I'm publishing my app to a vps everything works great when starting the app using runserver or normal testing with Gunicorn but when trying to run my server through Gunicorn the driver keeps crushing any help please ? ideas to help fix the problem -
How to implement one-way data transfer at specific intervals using SSE or WebSockets?
I'm working on a web application where I need to send data from the server to the client at specific times rather than continuously. I want to achieve this using either Server-Sent Events (SSE) or WebSockets. Requirements: One-way communication: Data only flows from the server to the client. Timing control: Data should be sent only at predefined intervals or specific triggers, not continuously. Questions: Can I use SSE for this purpose, and if so, how would I structure the server to send messages only at specified times? Would using WebSockets be a better approach for sending timed messages? If yes, how would that be implemented? Are there alternative methods (like HTTP polling or long polling) that could suit my needs better? I initially tried using Server-Sent Events (SSE), but I found that it sends data continuously, which isn't what I need. -
Hi, I'm new to the Django. I wanted to know how to bind selected objects to another model object at once on web page (like a checkbox)
I wanted to know how to create a model object by binding multiple other selected objects at once on a web page (like a checkbox or something). For example If I want to create a model named group for university but I need to include students from another model to this group excluding some of them (not all of the given students will be included). So, I was not able to create a form to choose all of them or exclude some of them at once, please help. Thanks in advance. -
Timeout error when uploading PDF and CSV files in Django app on o2switch server
I deployed a Django application on an o2switch server and I am trying to upload files to my media folder. My code works perfectly for .txt and .xlsx files, but it does not work for .pdf or .csv files. I get a timeout error, and it seems that the request does not even reach the server, because nothing appears in the logs. I tried to do a test with a PHP script on the same domain, and it works for all file types. So the problem seems to come either from the Django Rest Framework application, or from a specific configuration on o2switch. As a reminder, uploads work fine with .txt files, but I get a timeout for .pdf and .csv files. Do you have any ideas on what could cause this behavior? Is it a problem related to Django Rest Framework or to the o2switch configuration? and python 3.8.18 Thanks in advance for your help import os import sys sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = 'Back_end_Gaz_elec.settings' import django.core.handlers.wsgi from django.core.wsgi import get_wsgi_application SCRIPT_NAME = os.getcwd() class PassengerPathInfoFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset … -
Calculate max parallel elements by time in elasticsearch
I need to calculate max parallel people survey in elastic search. Mapping for this fields are: "start_at": {"type": "date"}, "end_at": {"type": "date"}, So, for one week i need to know with accuracy ~10s when in our system was max people and how much of them :-) Thx for help :-) "aggs": { "seconds_histogram": { "date_histogram": { "field": "start_at", "fixed_interval": "1s", "min_doc_count": 0, "extended_bounds": { "min": ..., "max": ... } }, "aggs": { "active_surveys": { "bucket_script": { "buckets_path": { "start": "_key", "end": "_key" }, "script": """ // Survey should have started before or at the bucket second and ended after or at the second. if (doc['start_at'].value.getMillis() <= params.start && doc['end_at'].value.getMillis() >= params.end) { return 1; } else { return 0; } """ } } } } -
Creating an SPA - use AJAX or django urls?
I am building a website as a school project, which should use django for the backend and vanilla js for the frontend. My question is, for loading different html files, is it better to use AJAX or django urls? I am not sure if using different django urls would make the content load dynamically, as it is required by a SPA. If there is a better way to load my content, please let know. I will really appreciate any help with this. -
Django Wagtail, React Native and 3rd Party Signup and Signin
I'm working on a marketplace platform. My sellers have a web portal to manage their stores. My buyers have a react native mobile application to access the platform. My server is running on django wagtail. I am using django allauth and I'm able to login to my django server from my mobile application. Using username and password and it creates a jwt which my app uses to consume my django api's. However I would like for my mobile users and web portal users to signup using Google and Facebook providers. Using the following two links documentation and doc. I have sort of an idea of the flow. However I'm not clear how to use it with firebase as the examples is directly to the 3rd party provider of github. Based on my research I keep coming across Firebase, how will it play nice with django allauth social? And will my web portal and mobile app need different integration methods? I came across this post but the answer doesn't seem complete because if Django doesn't have anything to do with this flow how will it know a user is authorised to consume my API's? -
Access Denied while sending email from AWS SES in ElasticBeanstalk (Django application)
I have recently (noticed) that I'm getting the following error in my Django application running on AWS An error occurred (AccessDenied) when calling the GetSendQuota operation: User: arn:aws:iam::123412341234:user/USER-IAM-NAME is not authorized to perform: ses:GetSendQuota with an explicit deny in an identity-based policy My user has full SES access via the direct policy AmazonSESFullAccess. In order to ensure GetSendQuota is explicitly stated, I have also added this inline policy { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "ses:SendEmail", "ses:SendRawEmail", "ses:GetSendQuota" ], "Resource": "*" } ] } I do not understand how to fix this. Help would be greatly appreciated -
What is the best option for Django+Celery in Google Cloud run?
We currently have an application which runs in Django and background tasks are in Celery. Now, we need to move to Google Cloud Run, and how to Celery in that case, since celery can not be run in Google cloud run (because it is serverless). I have background tasks like generate video (which may take around 10 minutes) and like generate image, and also sending requests to other services asynchronously. For sending asynchronous request to other services, I used Google Tasks, but the functions for generating video is in my service actually, but Google Task requires to send in this format: "http_request": { 'http_method': tasks_v2:HttpMethod.POST, 'url': url } Is there something that I need to put my function just in background task as celery does simply? What will be the best option for my case to use for background tasks? -
Can you use HTMX with datatables?
I have this in my datatables: columns: [ { data: 'product.item_code', className: 'text-start align-middle', render: function (data, type, row) { return '<a href="#" class="btn btn-primary" hx-post="/app/function/" hx-trigger="click" hx-target="#details" hx-swap="beforeend">' + row.product.item_code + '</a>' } } I am not able to get into the hx-post function when the anchor tag is in the datatable but works if it's in a regular HTML page -
After adding the HOST setting in django, I get a utf-8 error when creating a superuser
I am new to django. I am trying to open my project with a postgresql database in docker. There is no problem in the build process, but when I try to create a superuser, I get a utf-8 error. yml file services: app: build: . volumes: - .:/project ports: - "8000:8000" image: app:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 depends_on: - db postgres_db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data ports: - '5432:5432' environment: - POSTGRES_DB=project - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db volumes: postgres_data: {} docker file FROM python:3.12.7 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ libpq-dev build-essential WORKDIR /project COPY requirements.txt /project/ RUN pip install -r requirements.txt COPY . . settings database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'firstproject', 'PASSWORD': 'postgres', 'USER':'postgres', 'HOST': 'postgres_db', 'PORT': 5432, } } Error Traceback (most recent call last):File "D:\django code\first\firstp\manage.py", line 22, in <module>main()File "D:\django code\first\firstp\manage.py", line 18, in mainexecute_from_command_line(sys.argv)File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_lineutility.execute()File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management_init_.py", line 436, in executeself.fetch_command(subcommand).run_from_argv(self.argv)File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argvself.execute(*args, **cmd_options)File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 88, in executereturn super().execute(*args, **options)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 457, in executeself.check_migrations()File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 574, in check_migrationsexecutor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\executor.py", line 18, in initself.loader = MigrationLoader(self.connection)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\loader.py", line 58, … -
Django returns "Authentication credentials were not provided" when I attempt token authentication
(I tried the solutions in similar questions, but they didn't work for me). I am creating a simple Django REST based web-app, where a user will register, create some events, log in later and view events. Here's the event's view: class EventGetCreate(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): created_user = request.user events = Event.objects.filter(creator=created_user) serializer = EventSummary(events, many=True) return Response(serializer.data) Its urls.py is as below: from django.urls import path, include from . import views app_name = 'event' urlpatterns = [ ... path('eventviewall/', views.EventGetCreate.as_view()), ] In core/urls.py, I have this to obtain the token: from .views import UserViewSet from rest_framework.authtoken.views import ObtainAuthToken, obtain_auth_token app_name = 'core' router = routers.DefaultRouter() router.register('users', UserViewSet) urlpatterns = [ path('auth/', obtain_auth_token), path('register/', include(router.urls)), ] Using postman, I can login successfully and get the token: Send request to http://127.0.0.1:8000/api/auth/ and get the following (example token): { "token": "xxyyzz" } Now what I want to do is to send this token in a get request, and view the events the user created. I send the request to http://127.0.0.1:8000/event/eventviewall/, with the above token set in Authorization tab -> Bearer token. However, I get the following response: { "detail": "Authentication credentials were not provided." } Now, if …