Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM filter on datetime understands entries with a 'Z' offset, but not '+0000' offset
I have a MySQL database that mirrors a salesforce database. My table has a column for "createddate" that is contains ISO-8601 datetime entries. Some of the entries have an offset of "Z" and some of the entries have an offset of "+0000" like this: 2025-01-20T17:18:18.000Z 2025-01-20T18:11:10.000Z 2025-01-20T17:27:55.000+0000 2025-01-20T17:29:46.000Z 2025-01-20T17:28:19.000+0000 When I attempt to filter on a certain date, the filter ONLY returns lines that have a "Z" offset. lines with "+0000" are not returned. My filter code looks like: receipts = Receipt.objects.filter(createddate__date='2025-01-20').count() As far as I can tell, both formats conform to ISO-8601. I do have USE_TZ set to true in my settings.py the field is configured in models.py like: createddate = models.CharField(db_column='CreatedDate', max_length=28, blank=True, null=True) Relatively new to django and its ORM, I'm currently working around with a raw SQL query but I'd rather do it natively if possible. -
Duplicate the content of the block in Django template
Suppose I have the following code in base.html: <meta name="description" content="{% block description %}Some description{% endblock %}"> Other templates that extend base.html, override the contents of the block and so each page gets its own description. What if I want to add <meta property="og:description" content="" />, where the value of the content should equal the above value? How can I add the contents of the block into another place? -
Javascript display raw JSON instead of rendering the HTML content like the "index" button
I'm developing a Django web application that allows users to follow each other and view a feed of posts from the users they follow. I have a button that triggers an AJAX request to a Django view designed to fetch and render the relevant posts. My Django view correctly retrieves the posts from users the currently logged-in user follows and returns them as a JSON response. However, when my JavaScript code receives this response, it doesn't render the posts into the page as HTML. Instead, the browser displays the raw JSON data. I expect the JavaScript to use the JSON data to update the page with rendered HTML content representing the posts, but this isn't happening. How can I ensure that my JavaScript correctly processes the JSON and renders the posts as HTML? thanks for helping ❤️ post.js: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views const index = document.querySelector('#index') const following = document.querySelector('#following') if(index) { index.addEventListener('click', () => load_data('index')); } if (following) { following.addEventListener('click', () => load_data("following")); } // By default, load the index load_data('index'); }); function load_data(type) { console.log("type:", type); let url; if (type == "index") { url = "/post" } else if (type == "following") … -
How paginator active?
1 with bootstrap 5.3 when browsing not get active the paginator in the page attach imagen enter image description here I want to navigator this activated for each page. For example imagen enter image description here My Code <nav aria-label="Page navigation example"> <ul class="pagination"> {% if tipomaterial.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ tipomaterial.previous_page_number }}">&laquo;</a></li> {% endif %} {% for page_number in tipomaterial.paginator.page_range %} {% if items_page.number == page_number %} <a class="page-link" href="?page={{ tipomaterial.page_number }}"> {{ page.number }} </a> {% else %} <li class="page-item" aria-current="page"> <a class="page-link" href="?page={{ tipomaterial.page_number }}"> {{ page.number }} </a> </li> {% endif %} {% endfor %} {% if tipomaterial.has_next %} <li class="page-item"><a class="page-link" href="?page={{ tipomaterial.next_page_number }}">&raquo;</a></li> {% endif %} </ul> </nav> -
s3 upload timeout on dockerized Digital Ocean setup
I have a S3 compatible storage and a Droplet server on Digital Ocean. The dockerized Django app I am running is trying to sync static assets to the storage. This fails from the Droplet server/Docker container, but not when accessing the same S3 storage from my local setup. I can also test the upload straight from the server (outside the dockerized app) and this works, too. So something about the Docker setup is making the S3 requests fail. I made a simple test case, in s3upload.py with foobar.txt present in the same directory: from boto3.s3.transfer import S3Transfer import boto3 import logging logging.getLogger().setLevel(logging.DEBUG) client = boto3.client('s3', aws_access_key_id="…", aws_secret_access_key="…", region_name="ams3", endpoint_url="https://ams3.digitaloceanspaces.com") transfer = S3Transfer(client) bucket_name = "…" transfer.upload_file("foobar.txt", bucket_name, "foobar.txt") The error I am seeing when calling this from the docker container is: Traceback (most recent call last): File "/usr/local/lib/python3.13/site-packages/boto3/s3/transfer.py", line 372, in upload_file future.result() ~~~~~~~~~~~~~^^ File "/usr/local/lib/python3.13/site-packages/s3transfer/futures.py", line 103, in result return self._coordinator.result() ~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/usr/local/lib/python3.13/site-packages/s3transfer/futures.py", line 264, in result raise self._exception File "/usr/local/lib/python3.13/site-packages/s3transfer/tasks.py", line 135, in __call__ return self._execute_main(kwargs) ~~~~~~~~~~~~~~~~~~^^^^^^^^ File "/usr/local/lib/python3.13/site-packages/s3transfer/tasks.py", line 158, in _execute_main return_value = self._main(**kwargs) File "/usr/local/lib/python3.13/site-packages/s3transfer/upload.py", line 796, in _main client.put_object(Bucket=bucket, Key=key, Body=body, **extra_args) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.13/site-packages/botocore/client.py", line 569, in _api_call return self._make_api_call(operation_name, kwargs) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^ … -
Django HTTP response always sets `sessionid` cookie and session data do not persist
I have created a custom backend and related middleware which log users in on the sole condition that an ID_TOKEN cookie is passed along with the request (authentication is done by AWS Cognito + Lambda Edge, managed by an AWS CouldFront). My code is extensively based on django.contrib.auth.backends.RemoteUserBackend and its related middleware middleware django.contrib.auth.middleware.RemoteUserMiddleware. While dealing with custom session data is working fine both locally and in a Docker container using runserver + unit tests do pass, I lose all session data in production (code running in a container on AWS ECS) from one request/response to another. From what I can see in my Firefox network tab, a set-cookie header is always sent with the HTTP response, causing session data to be lost. I guess they must be flushed as well on the back-end side (sessions use database store, production is running on gunicorn). I have set SESSION_COOKIE_SECURE = True in production but it did not solve the issue. Moreover, using django_extensions and its runserver_plus with an auto-generated certificate to use HTTPS locally as well did not allow me to reproduce the issue. Here is one set-cookie example: set-cookie sessionid=rlc...tn; expires=Mon, 03 Feb 2025 14:29:53 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax; … -
Django DB Connection Pool Shared Across Workers?
In Django, are DB connections in the Psycopg 3 DB Connection Pool shared between gevent gunicorn workers or does each worker spawn its own DB connection pool? https://docs.djangoproject.com/en/5.1/ref/databases/#connection-pool -
RUN pip install --no-cache-dir -r requirements.txt installing but no working with Docker
I've trying to use docker for a couple of projects, one is a Django and another is a python telegram bot; But in both cases the problem is that no matter how I copy or install requirements.txt into the container, the libraries apparently get installed, but then all of a sudden I get errors like this in the main python container: telegram-bot-container | File "/app/run.py", line 15, in <module> telegram-bot-container | import logging, mysql_handler, cmc_handler, constants telegram-bot-container | File "/app/mysql_handler.py", line 2, in <module> telegram-bot-container | from decouple import config telegram-bot-container | ModuleNotFoundError: No module named 'decouple' And I have to install all missing libraries like this, as if requirements.txt was redundant!: pip install python-telegram-bot mysql-connector-python python-coinmarketcap python-decouple Please help me identify the problem. My whole Dockerfile: FROM python:3.10-slim WORKDIR /app COPY ./requirements.txt /app/ RUN python -m pip install --upgrade pip && \ pip install --no-cache-dir -r requirements.txt || echo "Skipping problematic package." && \ pip install python-telegram-bot mysql-connector-python python-coinmarketcap COPY . /app EXPOSE 8081 CMD ["python", "run.py" ] I tried rebuilding with/without caching. I can see that the packages are being installed in logs. -
Stripe 404 with DJStripe and Django
I am running a django app using stripe for payments. Upon running stripe cli I am encountering 404 errors when triggering payment events. project level urls.py path('api/payments/', include('payments_app.urls')) payments_app level urls.py: path('stripe/', include('djstripe.urls', namespace='djstripe')) I am consistently encountering the following errors: 2025-01-19 22:04:48 --> customer.created [evt_1QjCEGKCdat1JCnURBfuIFLH] 2025-01-19 22:04:48 <-- [404] POST http://localhost:8000/api/payments/djstripe/ [evt_1QjCEGKCdat1JCnURBfuIFLH] I can assure you that the API keys have been set correctly as I was able to successfully sync from the products and prices. I ran many permutations of the following url with changing the urlpatterns stripe listen --forward-to http://localhost:8000/api/payments/stripe/webhook I tried running: curl -X POST http://localhost:8000/payments/stripe/webhook -H "Content-Type: application/json" -d '{}' It also give a 404 -
Django refuses connection on AWS instance
I have a django app which is close to the default install app. In settings.py I have DEBUG = False ALLOWED_HOSTS = ['*'] I have added a url server/get_something which I can request and returns fine when I am running the server locally using python manage.py runserver I have installed and run my app on an AWS instance using port 7500, and I have opened that port to all addresses in the AWS security group like this: However when I make my request from a remote computer (to the AWS instance) I get a "refused to connect" error. There is no relevant printed output on the django process. It is worth noting that if I try to connect to a different port, it times out, so I think that the request is getting past AWS' firewall. But I can't work out why it isn't getting to django on the instance. Also, I have used curl locally on the AWS instance: curl 127.0.0.1:7500/server/get_something And this works fine. -
ModuleNotFoundError: No module named 'wagtail.contrib.modeladmin' when i try to write "wagtail.contrib.modeladmin' on base.py file it rise this error
from django.contrib import admin from .models import Subscribers @admin.register(Subscribers) class SubscriberAdmin(admin.ModelAdmin): """Admin configuration for Subscribers.""" model = Subscribers menu_label = "Subscribers" menu_icon = "placeholder" menu_order = 290 add_to_settings_menu = False exclude_from_explorer = False list_display = ("email", "full_name",) search_fields = ("email", "full_name",) this was my admin.py file -
Django 5.0.x async with raw query set & iterator
I have a raw query set that returns a few millions of elements. Actually, I use the iterator() function of django to improve performances. The problem I have here, is that I want to make the function where the query is called asynchronous. Because of that, I can't make Django raw queryset anymore because I get this error : django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Using sync_to_async makes the use of iterator impossible. There is the aiterator() function, but it doesn't work on raw query set.. How can I use iterator with a raw query set in an asynchronous context ? Code : def _get_elements_to_process(self): return Elements.objects.raw( """ My query """, ) async def fetch_data(self): for element in _get_elements_to_process().iterator(): # make some asynchronous action -
I can't create a new url on django
i've watched some tutorials on how to create a new simple url and for some reason it doesn't work, it looks like i didnt registred any urls even though i did. i created an app called 'Login' and registered it in the "INSTALLED APPS" list on settings.py of django : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Login.apps.LoginConfig', ] then i created the function called 'home' on the views file of the app, to show a phrase on the page: from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('Hello') and then i created a new url path on the urls.py file of the project, without a name at first, just (""): from django.contrib import admin from django.urls import path from Login.views import home urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), ] and when i use the (python manage.py runserver) command it just got back to the "success install" page of django, the one with the little rocket. Then I tried using a name for the url ("home/"): from django.contrib import admin from django.urls import path from Login import views urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.home) ] but when i access the (localhost:8000/home/) it says … -
python package `drf-comments` not being recognized
i am developing a rest-based django project. i want to implement a commenting system in my project; but it has to be decoupled from the other apps. therefore, deepseek suggested to use drf-comments in my project. the whole thing seems appealing; as it does not require writing any model, view, serializer and url. deepseek just told me to add the urls coming from the drf-comments package and i did so. everything looks fine; but when i attempt to run the command python manage.py makemigrations or the migrate command, i get the error: ModuleNotFoundError: No module named 'drf_comments' and i got back to my chatbots (deepseek and blackbox) and they told me to go back, delete-recreate the venv to make sure everything works fine; but i know it is fine. does anybody know what's the problem with this python package (drf-comments)? maybe it is not supported anymore. additional information: python version: Python 3.11.4 the pip list: asgiref 3.8.1 certifi 2024.12.14 cffi 1.17.1 charset-normalizer 3.4.1 defusedxml 0.8.0rc2 Django 5.1.4 djangorestframework 3.15.2 djangorestframework_simplejwt 5.4.0 djoser 2.3.1 drf-comments 1.2.1 drf-nested-routers 0.94.1 idna 3.10 oauthlib 3.2.2 pip 24.3.1 pycparser 2.22 PyJWT 2.10.1 python3-openid 3.2.0 requests 2.32.3 requests-oauthlib 2.0.0 setuptools 65.5.0 social-auth-app-django 5.4.2 social-auth-core 4.5.4 sqlparse … -
What component might emit 'Request max total header size exceeded'
I am posting documents into paperless-ngx via REST api. For some pdf documents the API reliably responds with {"detail":"Multipart form parse error - Request max total header size exceeded."} I checked one of the offending documents and found it to be a normal, valid PDF of about 180 kb size. There should not be too much fuss about it, yet I have that error. Now I am wondering where this error might come from and how to get around it. Does it come from GUnicorn, Django or maybe the application itself? -
I can't use UUID with DJ-STRIPE: DJStripe: Account has no field named 'uuid'
I am attempting to setup djstripe bit am encountering the following error. settings.py: DJSTRIPE_SUBSCRIBER_MODEL = 'auth_app.CustomUser DJSTRIPE_FOREIGN_KEY_TO_FIELD = 'uuid' AUTH_USER_MODEL = 'auth_app.CustomUser' This is my models.py. Note that I am using abstractcuser in order to use email as the username. from django.db import models from django.contrib.auth.models import AbstractUser import uuid from cuser.models import AbstractCUser class CustomUser(AbstractCUser): uuid = models.UUIDField(default=uuid.uuid4, unique=True) email = models.EmailField(unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email This is the error that I am facing: raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: Account has no field named 'uuid' I have tried to delete the migrations folder and the database file but the issue persists. Please let me know if you require any further information. Thank you. -
Django relation on two database columns
I am using django to interface with an existing database that I have no control over. The database frequently uses multiple columns for making relations and has uniqueness over all of those columns. The django inspectdb model generator correctly identified these as unique_together = (('foo', 'bar'), ('foo', 'bar'),), resulting in the following model: class A(models.Model): foo = models.IntegerField(db_column='FOO', primary_key=True) bar = models.IntegerField(db_column='BAR') class Meta: managed = False db_table = 'A' unique_together = (('foo', 'bar'), ('foo', 'bar'),) Now there is another table whose entries relate to that table on both columns. When querying using SQL I would relate them like this: SELECT * FROM A LEFT JOIN B ON A.foo = B.foo AND A.bar = B.bar However inspectdb failed to correctly map the two columns being used in a relating table: class B(models.Model): foo = models.OneToOneField(A, models.DO_NOTHING, db_column='A', primary_key=True) bar = models.ForeignKey(A, models.DO_NOTHING, db_column='A') The above is what it generated, however in reality it is a many-to-one relationship to table A. This then causes an error at runtime because the column bar in table A is not unique. Can I somehow define this relationship in a django model? And how do I query this efficiently so that django generates a JOIN … -
m2m_changed instance when in reverse
I have the following signal: @receiver(m2m_changed, sender=User.cars.through): def car_added_to_user(sender, instance, action, *kwargs): if action in ("post_add",): cache.delete(f"user-{instance.pk}") I can trigger it as expected when doing: User.cars.add(car) but if I also want to delete the user from the cache in this case, what do I do? Car.user_set.add(user) as in this case the instance is a Car object and not a User object. -
why "django-admin --version" command doesn't give any output?
I had install django successfully and I change script path also but still I didn't receive any answer for (django-admin --version) command i type django-admin --version I need the installed version as the output.But I didn't receive anything. -
django-tenant-schema migration issue: IntegrityError: insert or update on table "auth_permission" violates foreign key constraint
requirements.txt: Django==4.2.16 django-tenant-schemas==1.12.0` django-allauth==65.0.2 Added a new django model, then ran migrations: ./manage.py migrate_schemas --schema=public ./manage.py migrate_schemas --schema=myschema The first command runs fine. The second command gives this error: django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "auth_permission_content_type_id_2f476e4b_fk_django_co" DETAIL: Key (content_type_id)=(115) is not present in table "django_content_type". Indeed, the auth_permission table does not (yet) contain any permissions related to the new model. But actually, value '115' is present in the public.django_content_type table, with the right app_label and model info. So unclear why this error is raised. Maybe the migration is not looking in the public schema? But other migrations have been running for ages, only the new table creation seems to cause a problem now. -
How to get ckeditor5 link settings to work with Django project
I installed django-ckeditor-5 and I am using it as the editor for a django-machina forum. The editor displays on the forum and basically works correctly. However, I want links to open in a new tab when clicked and I want "https://" to be automatically inserted if the user does not add it to their link when using the link button. I can not get the link attributes to work. Here are my machina settings: MACHINA_MARKUP_LANGUAGE = None MACHINA_MARKUP_WIDGET = 'django_ckeditor_5.widgets.CKEditor5Widget' Here are my ckeditor config settings: CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ], }, 'link': { 'addTargetBlank': True, # Open links in a new tab 'defaultProtocol': 'https', # Default protocol for links is https 'plugins': ['AutoLink'], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', ], 'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'code','subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable',], 'image': { 'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter', ] }, # 'table': { # 'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells', … -
i have a problem with the importation of wagtail.contrib.settings.models import ModelSettings
from django.db import models from wagtail.admin.panels import FieldPanel, MultiFieldPanel from wagtail.contrib.settings.models import ModelSettings,register_setting @register_setting class SocialMediaSettings(ModelSettings): """Social media settings for our custom website.""" facebook = models.URLField(blank=True, null=True, help_text="Facebook URL") twitter = models.URLField(blank=True, null=True, help_text="Twitter URL") youtube = models.URLField(blank=True, null=True, help_text="YouTube Channel URL") panels = [ MultiFieldPanel([ FieldPanel("facebook"), FieldPanel("twitter"), FieldPanel("youtube"), ], heading="Social Media Settings") ] i have already upgrade to the latest version of wagtail but still rise the ImportError: cannot import name 'ModelSettings' from 'wagtail.contrib.settings.models -
simplejwt & allauth - auth cookie not sent from browser to django backend
I have a Django backend that uses allauth and simplejwt (both provided by dj-rest-auth) for authentication. When I make API requests using an API client (Bruno), my auth cookies containing JWT tokens are passed, and the server responds. But, I can't achieve the same thing in JS from the browser. The authentication cookies are received, but not passed in subsequent requests: minimal front-end JS: (async () => { console.log("logging in...") const loginResponse = await fetch('http://127.0.0.1:8000/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'test', password: 'securepassword123' }) }) const loginData = await loginResponse.json(); // response contains `set-cookie` headers // vv prints JSON containing "access", "refresh", "username", etc. console.log(loginData) if (!loginResponse.ok) { console.log('login failed :(') return } console.log("getting user info...") const userResponse = await fetch('http://127.0.0.1:8000/api/user', { credentials: 'include' }); const userData = await userResponse.json(); // vv prints `{detail: 'Authentication credentials were not provided.'}` console.log(userData) if (!userResponse.ok) { console.log("user data fetch failed :(") } })(); I've already set up CORS, allow-credentials, etc. in Django: # dj-rest-auth settings --------------------------------- # src: https://medium.com/@michal.drozdze/django-rest-apis-with-jwt-authentication-using-dj-rest-auth-781a536dfb49 SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ) } # djangorestframework-simplejwt SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } # dj-rest-auth REST_AUTH = … -
django-allauth with steam
as describe in this [issue on github][https://github.com/pennersr/django-allauth/issues/3516], my login method which is working by the way, seems to throw an exception everytime it is used: Missing required parameter in response from https://steamcommunity.com/openid/login: ('http://specs.openid.net/auth/2.0', 'assoc_type') Traceback (most recent call last): File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/message.py", line 481, in getArg return self.args[args_key] ~~~~~~~~~^^^^^^^^^^ KeyError: ('http://specs.openid.net/auth/2.0', 'assoc_type') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/consumer/consumer.py", line 1286, in _requestAssociation assoc = self._extractAssociation(response, assoc_session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/consumer/consumer.py", line 1402, in _extractAssociation assoc_type = assoc_response.getArg(OPENID_NS, 'assoc_type', no_default) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/message.py", line 484, in getArg raise KeyError((namespace, key)) KeyError: ('http://specs.openid.net/auth/2.0', 'assoc_type') assoc_type is misssing from steam respone. These are my app settings: INSTALLED_APPS = [ ... # social providers "allauth.socialaccount.providers.openid", "allauth.socialaccount.providers.steam", ... ] MIDDLEWARE = [ ... "allauth.account.middleware.AccountMiddleware", # social providers ... ] AUTHENTICATION_BACKENDS = ( "allauth.account.auth_backends.AuthenticationBackend", "django.contrib.auth.backends.ModelBackend", ) SOCIALACCOUNT_PROVIDERS = { "steam": { "APP": { "client_id": STEAM_SECRET_KEY, "secret": STEAM_SECRET_KEY, } }, } Did I miss something in my implementation ? Is there a way to avoid the raising of this exception ? -
dj-rest-auth access token not sent from react font-end to django back-end
I'm making an SPA with a React front-end and a Django back-end. For user authentication, I'm using dj_rest_auth, which wraps allauth to provide a REST API interface. dj-rest-auth provides a "login" endpoint that sends back access and refresh cookies. It also privides a "user" endpoint that returns the username, email, first name and last name. Both work as expected in my API client (Bruno), BUT, I can't get the "user" api to work in my front-end code. My browser doesn't send cookies to the server. Here are screenshots from Bruno. Notice how the cookies are saved, and fetching the user's info works: Here's my login request from my React app and the set-cookie headers (aka response cookies): // ... fetch(BACKEND_URL + "/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: username, password: password, }), }) .then(async (response) => { //... study_stream_auth_cookie=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzM3MjM3MTEyLCJpYXQiOjE3MzcyMzM1MTIsImp0aSI6IjNjZDc4ZjI3ZWYyNTQwMzI4MmVmNjAwODRiMjcxYzU0IiwidXNlcl9pZCI6NDB9.JK-SKSGMWuTBFm4JFk4-T8RqNEf2vwANrS4-h7P9UMY; expires=Sat, 18 Jan 2025 21:51:52 GMT; Max-Age=3600; Path=/; SameSite=Lax study_stream_refresh_cookie=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTc0NTAwOTUxMiwiaWF0IjoxNzM3MjMzNTEyLCJqdGkiOiJhMTljYjg1ZDI5Zjk0NTQyOWUzMjM2ODdmY2IxYzQ0YiIsInVzZXJfaWQiOjQwfQ.xvfB61xkq9NUzQSZeAJmXSYaFrYcSfrsJ9QX2u635LU; expires=Fri, 18 Apr 2025 20:51:52 GMT; Max-Age=7776000; Path=/; SameSite=Lax sessionid=qt2yxaiitghqavr74xvvl8icjlckq6by; expires=Sat, 01 Feb 2025 20:51:52 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure And here's my "user" GET request. Notice that the only cookie sent here is csrftoken which is unrelated. const response = await fetch(BACKEND_URL + "/api/auth/user/", …