Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking user login
I have thre templates admin_dash.html, customer_dash.html and assigment.html all extendin from a base.html template. The base.html comprises of sidebar.html and header.html(as includes) the admin_dash.html comprises of status.html, customers.html and requestTbl.html (i used include tag). base.html .{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet"> <title>{% block title %} Base {% endblock title %}</title> <link rel="shortcut icon" type="img/png" href="{% static 'img/Mwemo_logo.png' %}"> </head> <body> {% include 'garbage/header.html' %} <section class="main"> {% include 'garbage/sidebar.html' %} <div class="main--content"> {% block content %} {% endblock content %} </div> </section> <script src="{% static 'js/base.js' %}"></script> </body> </html> header.html {% load static %} <section class="header"> <div class="logo"> <i class="ri-menu-line icon icon-0 menu"></i> <a href=""><img src="{% static 'img/Mwemo_logo.png' %}" alt="mwemo inv logo" style="height: 50px; width: 100px; padding: 3px 0px 0px 30px;"> </a> </div> <div class="search--notification--profile"> <div class="search"> <input type="text" placeholder="Search Scdule.."> <button><i class="ri-search-2-line"></i></button> </div> {% if request.user.is_authenticated %} <p>User: {{ request.user }}</p> {% else %} <p>Kindly login!</p> {% endif %} <div class="notification--profile"> <div class="picon lock"> <i class="ri-lock-line"></i> </div> <div class="picon bell"> <i class="ri-notification-2-line"></i> </div> <div class="picon chat"> <i class="ri-wechat-2-line"></i> </div> <div class="picon profile"> <img src="assets/images/profile.jpg" alt=""> </div> </div> </div> … -
Django locale .po files not showing up in locales folder
I have been running into an issue setting up locales for my Django app. When I run the django-admin's makemessages command no resulting .po files show up in my {project_root}/locales folder. Here are the steps I followed to setup locales: Changes to settings.py MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] USE_I18N = True LOCALE_PATHS = [ osjoin(BASE_DIR, 'locale'), ] Solved missing dependencies Had to install GNU gettext (for windows) and added it to system PATH. Commands I ran python manage.py makemessages -l fr also tried: python manage.py makemessages -l fr both result in this output message but no files added to locales/: processing locale fr I also superstitiously tried to run the command as admin but didn't change much. I am also aware of these answers to the same question (9 years ago) but the answers didn't help. -
Docker doesn't see static updates on Django project
Until today, Docker had been successfully receiving my static updates. However, today, when I attempted to change my logo, nothing happened. Additionally, when I modified some CSS styles, I encountered the same issue. I tried running "python manage.py collectstatic," but it didn't resolve the problem. It's possible that Docker is not copying static files to the app directory anymore. But why? Until today, this process was functioning properly. -
Add external plugin using django-ckeditor
I'm trying to install this details plugin for CKEditor 4, using django-ckeditor. I can't find a syntax that makes the button appear for me. I've put the plugin folder at /static/js/lib/ckeditor-plugins/detail/. It contains a plugin.js. I can view that file in the browser at that URL. In my Django settings.py I have this (minimal example): CKEDITOR_CONFIGS = { "default": { "addExternal": ",".join( [ "detail", "/static/js/lib/ckeditor-plugins/detail/", "plugin.js", ] ), "toolbar": [ { "name": "paragraph", "groups": ["blocks"], "items": [ "Blockquote", "Detail", ] } ] } } But there's no extra Detail button next to the Blockquote one. The Network tab of web dev tools doesn't show the plugin's plugin.js being loaded. I've tried changing the "addExternal" to this: "addExternal": [ ("detail", "/static/js/lib/ckeditor-plugins/detail/", "plugin.js"), ], But it's no different. I feel I'm missing one crucial step or change. -
Tags are not being saved when using django-parler
I am using django-parler for translation and django-taggit for adding tags. But when I add tags inside translation field (because of using in multiple language) tags are not being saved in admin page. models.py class News(models.Model): translations = TranslatedFields( title=models.CharField(max_length=255), content=RichTextUploadingField(), tags=TaggableManager(), slug=models.SlugField(max_length=255, db_index=True), ) category = models.ForeignKey(Category) -
nginx proxy pass error with django [DOCKER]
I have a django backend running on docker using this docker-compose.yml file: version: '3.1' services: frontend: build: context: ./classificacao-frontend container_name: frontend restart: unless-stopped db: image: postgres:13 container_name: postgres environment: - POSTGRES_DB=services - POSTGRES_USER=services_user - POSTGRES_PASSWORD=supersecret volumes: - ./postgres:/var/lib/postgresql/data restart: unless-stopped backend: build: context: . dockerfile: ./pge-services/docker/dev/python/Dockerfile container_name: backend volumes: - /docker/classificacao/shared_files:/shared_files - /docker/classificacao/static_files:/static_files environment: - DJANGO_SETTINGS_MODULE=pge.settings_dev - POSTGRES_NAME=services - POSTGRES_USER=services_user - POSTGRES_PASSWORD=supersecret - POSTGRES_HOST=db - POSTGRES_PORT=5432 - CAIPORA_ADDRESS=http://10.0.134.130 - USER_SYSTEM=/api/usuario-sistema restart: unless-stopped depends_on: - db proxy: image: nginx:stable-alpine container_name: proxy mem_limit: 128m restart: unless-stopped volumes: - ./config/nginx.conf:/etc/nginx/nginx.conf - ./config/nginx.htpasswd:/etc/nginx/conf.d/nginx.htpasswd - /etc/letsencrypt:/etc/letsencrypt - /docker/classificacao/pge-services:/code - /docker/classificacao/shared_files:/shared_files - /docker/classificacao/static_files:/static_files ports: - 80:80 - 443:443 The django backend (here as the backend service on docker-compose.yml) is being called as the /backend url on the nginx proxy: upstream back{ server backend:8000; } location /backend/ { set $accept_language "pt-br"; proxy_pass http://back; } The problem is the django, running on port 8000, has the /admin and /api endpoints on it. When i hit my proxy at /backend, i.e http://localhost/backend/admin, it tries to access django at /backend/admin, which doesn't exists (it should be only /admin). If i try only /backend, it shows a Not Found: / in the backend log. Also for /backend/api. It should proxy_pass to … -
CustomOAuth2Error at URL (redirect_url_mismatch) Bad Request
Error occurs at that block of code: `class GoogleCalendarRedirectView(View): def get(self, request, *args, **kwargs): state_from_session = request.session.get('state') print(f"Stored State in Session: {state_from_session}") flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events'], state=state_from_session ) flow.redirect_uri = 'http://localhost:8000/en/accounts/rest/v1/calendar/redirect/' authorization_response = request.build_absolute_uri() **flow.fetch_token(authorization_response=authorization_response)** return redirect('http://127.0.0.1:8000/en/accounts/rest/v1/calendar/events/')` Debugger info: Stored State in Session: qQxetuwGbiBt9mwuz78jcVxQ39pkWZ Redirect URI: http://localhost:8000/en/accounts/rest/v1/calendar/redirect/ Stored State in Session: qQxetuwGbiBt9mwuz78jcVxQ39pkWZ client_secret.json redirect: "redirect_uris":["http://127.0.0.1:8000/en/accounts/rest/v1/calendar/redirect/" google console authorized redirect URLS: http://127.0.0.1:8000/en/accounts/rest/v1/calendar/redirect/ I tried to edit and add new redirect URLS such as 'http://127.0.0.1:8000/en/accounts/rest/v1/calendar/redirect' but then this error occurs: Access blocked: This application sent an invalid request. You can't sign in because this app sent an invalid request. Error 400: redirect_uri_mismatch -
ModuleNotFoundError: No module named 'whitenoise'
I am trying to run my app via command gunicorn --bind 0.0.0.0:8000 foodorderapp.wsgi I have placed everything following the documentations: import os import sys from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise from foodorderapp.settings import BASE_DIR os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'foodorderapp.settings') application = get_wsgi_application() application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'static')) application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'media')) I am running my app inside virtual environment but I installed the whitenoise : (foodorderenv) root@localhost:~/foodorderapp# python3 -m pip install whitenoise Requirement already satisfied: whitenoise in ./foodorderenv/lib/python3.11/site-packages (6.6.0) Here is my settings.py file STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] But I am getting this error: File "/root/foodorderapp/foodorderapp/wsgi.py", line 4, in <module> from whitenoise import WhiteNoise ModuleNotFoundError: No module named 'whitenoise' How can I solve this problem? -
Django pytest error - Invalid pk because user object (created with bakery) not found
I'm using DjangoRestFramework 3.13 and pytest 7.1. My API tests are currently failing due to errors on missing object when passing its primary key to serializer. I have the following fixture for creating API client with authenticated user @pytest.fixture() def user_account(db): def _user(**kwargs): return baker.make("accounts.UserAccount", **kwargs) return _user @pytest.fixture() def api_client(user_account): def _api_client(auth_user=None): if auth_user is None: auth_user = user_account() client = _CustomAPIClient() client.force_authenticate(auth_user) return client return _api_client The testing method looks like this: @pytest.mark.django_db def test_create_customobject_api_success(api_client, data): client = api_client() url = reverse("api-custom:list") response = client.post(url, data) assert response.status_code == status.HTTP_202_ACCEPTED assert response.data["status"] == "PENDING" assert response.data["task_id"] != "" Now, when I test this previous route that creates CustomObject associated to that user, I get the following error: rest_framework.exceptions.ValidationError: {'user': [ErrorDetail(string='Invalid pk "13c6e59c-51ba-44e0-b9b6-07501c636330" - object does not exist.', code='does_not_exist')]} This error occurs when my Celery task finishes and is about to create my CustomObject : serializer = CustomSerializer(data=custom_data) if serializer.is_valid(): serializer.save() return serializer.data else: logging.error("Custom serializer invalid: %s", serializer.errors) raise serializers.ValidationError(serializer.errors) The asynchronous task is being called from a Django view post method, and the custom_data has user property with user UUID : custom_data["user"] = request.user.uuid I checked if my api_client actually creates a valid user, and it does. … -
page loads as <pre></pre> on refresh
For some reason, I lose all page contents on refresh and the page renders as pre text? Everything is working as expected, I am able to fetch emails as needed, all buttons work, the url history is working as expected. I tried changing the order of calling functions, setting timeout for some functions but I still have the same issue? I have added images below of before and after refresh. before refresh after refresh document.addEventListener('DOMContentLoaded', function () { document.querySelectorAll('button').forEach(button => { button.onclick = function () { const section = this.dataset.section; var baseUrl = "/emails"; if (section === "compose") { history.pushState({ section: section }, "", baseUrl); composeEmail(); } else { history.pushState({ section: section }, "", baseUrl + '/' + section); loadMailbox(section); }; }; }); // default view loadMailbox('inbox'); }); window.onpopstate = function(event) { loadMailbox(event.state.section); }; var reply = false; function composeEmail(email, reply) { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#show-email').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; if (!reply && !email) { document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } else { document.querySelector('#compose-body').style.color = 'black'; document.querySelector('#compose-recipients').value = email.sender; document.querySelector('#compose-subject').value = `RE: ${email.subject}`; document.querySelector('#compose-body').value = `\n on ${email.timestamp} ${email.sender} wrote: ${email.body}`; } document.querySelector('#compose-form').addEventListener('submit', send_email); }; function loadMailbox(mailbox) … -
Celery logging in the same console as Django
I am using Celery to run tasks inside a Django API. The problem is that I get the logs of Django and Celery in two consoles separated and I want to show all the logs in Django. This is the logging config in settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "()": "colorlog.ColoredFormatter", "format": "%(log_color)s %(levelname)-8s %(asctime)s %(request_id)s %(process)s --- " "%(lineno)-8s [%(name)s] %(funcName)-24s : %(message)s", "log_colors": { "DEBUG": "blue", "INFO": "white", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "bold_red", }, }, "aws": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "filters": { "request_id": {"()": "log_request_id.filters.RequestIDFilter"}, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "verbose", "filters": ["request_id"], } }, "loggers": { # Default logger for any logger name "": { "level": "INFO", "handlers": [ "console", ], "propagate": False, }, }, } These are the celery config and an example of task: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green_navigation_back.settings") app = Celery("green_navigation_back") app.conf.update( CELERYD_HIJACK_ROOT_LOGGER=False, ) app.config_from_object("django.conf:settings", namespace="CELERY") @setup_logging.connect def config_loggers(*args, **kwargs): from logging.config import dictConfig from django.conf import settings dictConfig(settings.LOGGING) app.autodiscover_tasks() logger = get_task_logger(__name__) @shared_task(ignore_result=True, time_limit=3600) def optimization_email_task(request_data, user_email): logger.info("Preparing optimization") if "arn:aws" in settings.LAMBDA_URL: # Timeout must be lower than time_limit client_config = Config(connect_timeout=1800, read_timeout=1800) … -
Django Issue with multiple databases router | Connection not found
I'm currently working on a project where I'm trying to incorporate multiple databases. Allow me to break down what I've done so far: Django Version: I initiated the process by upgrading Django from version 4.2.1 to 5.0.1 while keeping my Python version constant at 3.10.2. Apps: Initially, my project had only two apps, but I've added a new one, resulting in a total of three. Importantly, there are no circular dependencies among them. All three apps have been properly added to the project's "Settings." Settings: In addition to the existing 'default' database, I introduced a new one named 'manager.' I adjusted the DATABASE_ROUTERS path accordingly in the project files. DATABASE_ROUTERS = ['routers.router-manager.ManagerRouter', 'routers.router-api.ApiRouter',] Routers File: Following the guidelines in the Django Documentation, I created a router file to manage the models for each app. Here's the configuration of my router file: class ManagerRouter: """ A router to control all database operations on models in the manager applications and api applications. """ route_app_labels = {"distributor_api", "manager_api"} def db_for_read(self, model, **hints): """ Attempts to read manager_api and distributor_api models go to """ if model._meta.app_label in self.route_app_labels: return "manager" return None def db_for_write(self, model, **hints): """ All writes (i.e. any create or update) … -
Mongodb aggregate pipeline query issue
Below is my pipeline query, I'm using pymongo in Django. pipeline = [ { "$match": { "planId": {"$eq": plan_id}, } }, { "$lookup": { "from": "plans", "localField": "linkedPlansIds", "foreignField": "id", "as": "linkedPlans", } }, {"$unwind": "$linkedPlans"}, { "$match": { "$or": [ {"id": {"$eq": plan_id}}, { "linkedPlans.planName": { "$regex": search_query, "$options": "i", } }, ] } }, { "$lookup": { "from": "plans", "pipeline": [ { "$match": { "$expr": { "$and": [ {"$ne": ["$id", plan_id]}, ] } } } ], "as": "plansList", } }, {"$unwind": "$plansList"}, { "$match": { "plansList.planName": { "$regex": search_query, "$options": "i", } } }, {"$skip": (page - 1) * limit}, {"$limit": limit}, { "$group": { "_id": None, "total_count": {"$count": {}}, "limit": {"$first": limit}, "page": {"$first": page}, "linkedPlans": {"$addToSet": "$linkedPlans"}, "plansList": {"$addToSet": "$plansList"}, } }, { "$addFields": { "plansList.isLinked": { "$in": ["$plansList.id", "$linkedPlans.id"] } } }, { "$project": { "total_count": 1, "page": 1, "limit": 1, "plansList.id": 1, "plansList.planName": 1, "plansList.isLinked": 1, "_id": 0, } }, ] So in this I have added a field isLinked to each objects in 'plansList'. By doing this { "$addFields": { "plansList.isLinked": { "$in": ["$plansList.id", "$linkedPlans.id"] } } } I thought it will correctly validate and set boolean there. what I want is that … -
How can I display a PDF file from a REST API in a PDF format in a React interface?
I am fetching a PDF file from a REST API using Axios and displaying it in a React interface with FileViewer. However, the content of the PDF file is displayed directly. How can I make it open the PDF file externally when clicking a button? -
Can anyone suggest me a tool to convert HTML to PDF in Python?
I'm seeking a reliable method to convert HTML to PDF. Although I've experimented with tools like pdfkit and wkhtmltopdf, I've encountered an issue with inconsistent styling. As more data is added, the styling becomes disrupted. Therefore, I am in need of a comprehensive solution that ensures consistent styling throughout and can automatically adjust if additional data is introduced. Tech stack I am using - Python, Django Here is a link for the sample PDF generated by pdfkit. The footer is appropriate and if the address is too big to the product is too big the issue starts popping Link - https://shorturl.at/sxL06 -
TypeError: ForeignKey.__init__() got multiple values for argument 'on_delete'
I am trying to define a foreign_key in a model in Django. But I am getting the error "TypeError: ForeignKey.init() got multiple values for argument 'on_delete'" The way I define the field is like this: class School(BaseModel): student_number = models.ForeignKey(Student,_("student_number"), max_length=200,on_delete=models.CASCADE) I don't really see why I am getting this error, because I have exact same implementation in other classes, and they do not raise an error. -
django - display the units of the selected item
Items model has units which is foreign to Units model. Now when we select the item in stock form, how to display the units of the selected item? models.py: class Units(models.Model): name = models.CharField(max_length=255, unique=True) class Items(models.Model): name = models.CharField(max_length=255, unique=True) units = models.ForeignKey(Units, on_delete=models.CASCADE, null=True, blank=True, related_name='units_items') class Stock(models.Model): item = models.ForeignKey(Items, on_delete=models.CASCADE, null=False, blank=False, related_name='item_stock') - - - - - - - - - - - - - - - - - - - - - - - - - - - - forms.py: class StockForm(forms.ModelForm): class Meta: model = Stock fields = ['item'] template: <div class="col-md-4 pl-0"> {{ formsingle.item|as_crispy_field }} </div> <div class="col-md-1 p-0"> <span></span> //here how to show related units when any item is selected </div> -
Django: Unknown command: 'collectstatic' when using call_command
I have a Django project with "django.contrib.staticfiles" in INSTALLED_APPS. Therefore, I can run ./manage.py collectstatic. But I need to use call_command. Running python -c 'from django.core.management import call_command; call_command("collectstatic")' results in django.core.management.base.CommandError: Unknown command: 'collectstatic' What am I doing wrong? Shouldn't the 2 commands be absolutely identical? Obviously, environments, paths, etc are correct in both cases. I am running both commands from the same shell in a docker container. -
Passing user's local timezone to celery in django app
I have a requirement where i want to show date time in user's local datetime. For which I have added a middleware code in django which gets the local date time from user's session through browser and activate that session. In my django settings.py I have added the timezone which is by default 'America/New york' Now I have celery where the database operations are performed asynchronously. But in celery the timezone which I am activating in middleware is not getting through. It is always picking it up from django settings.py file. If i remove the default timezone setting then it is taking the timezone as 'America/Chicago'. Below is my code for Middleware # middleware.py from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_timezone = request.GET.get('user_timezone', 'America/New_York') request.session['user_timezone'] = user_timezone response = self.get_response(request) return response And here is my code for celery task # tasks.py from celery import Celery, Task from django.contrib.sessions.models import Session from django.utils import timezone app = Celery('yourapp', broker='pyamqp://guest@localhost//') class TimezoneAwareTask(Task): def __call__(self, *args, **kwargs): # Get user timezone from session or use a default user_timezone = self.get_user_timezone(kwargs.get('session_key')) # Set the timezone for the task execution timezone.activate(user_timezone) try: result = super(TimezoneAwareTask, … -
im working on a django project as a total beginner . block content end block is not working and the browser renders raw code
here is my directoryworkspace base.html : frontpage.html : output im getting :enter image description here i tryed removing spaces within block tags ..but nothing works , the raw django code is displayed in the browser. what am i missing? . can someone please help me with this. -
DRF If there is a way how to save a fieldset in serializer?
I encountered a problem when trying to save fieldset data in the serializer. serializer.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'field_1', 'field_2', ) views.py class MyAPIView(generics.GenericAPIView): def post(self, request, *args, **kwargs): my_serializer = MyModelSerializer(data=request.data, many=True) # return [] One solution is to use many=True. However, the issue is that the serializer requires data in the format of data={'field_name': 'value', ...}, while request.data returns 'field_1': ['value_1', 'value_2']. Is there a way to work with fieldsets via serializer? -
python dango excel file open webserver
enter image description hereenter image description hereenter image description hereenter image description here 제가 파이썬 django로 작성한 파일인데 runserver하면 글자는 나오는데 csv로 된 엑셀파일이 띄우기가 안돼네요ㅜㅜ 왜 그런것일까요? 혹시 제 생각에는 view파일에 csv define이 구체적으로 정의가 안내려 그런것인가요? 근데 인터넷과 gtp 활용해보니 csvTomain함수로 엑셀 불러오기가 가능하다고 저는 그렇게 이해 하고 있습니다. -
In Django, where does the "data" field come from in the Serializer class?
I see in a bunch of django code, especially in viewsets, that when serializer is initialized like the following: class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post']) def set_password(self, request, pk=None): user = self.get_object() **serializer = PasswordSerializer(data=request.data)** the data argument is always being passed in the instantiation of a Serializer instance. But I feel like I have been researching django documentation everywhere and I can't seem to find a reference to this data argument. I really want to know what exactly is data doing here, where does it come from, why is information about it so hidden? I tried researching the official django rest framework documentation, as well as scoured several Medium articles to no avail. -
Javascript function not loading in Django template
I have a HTML tag that is supposed to run a function in my javascript file (app.js) when it gets clicked (this is implemented using the onclick tag property) but instead I get the following error: Uncaught ReferenceError: summon_chat is not defined at HTMLLIElement.onclick But when in my javascript file I code something like this: const list-item = document.querySelector('#listId') list-item.onclick = function () { my_function()} Then the onclick event works, what am I doing wrong? My base.html file is located at templates/layouts/ and my index.html is located at templates/ This is my index.html fragment that calls the function: <li onclick="console.log('CLICKED'); summon_chat(this);" class="list-group-item p-3"> This is my base.html: {% load static %} <!DOCTYPE html> <html lang="en" data-bs-theme="light"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock title %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <script src="https://unpkg.com/htmx.org@1.9.10" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script> <script src="{% static 'app.js' %}" type="module"></script> {% block script %}{% endblock script %} </head> <body> <div class="container-fluid"> <main>{% block content %}{% endblock content %}</main> </div> </body> </html> I already checked the dev console in my browser and the javascript file is loading correctly, I even added a console.log … -
Django - Redis Sessions not being recognized by downstream microservices from user_service
I am writing a Django framework based on Django Rest Framework with Redis enabled for authenticated sessions. That way my downstream micro-sevices can use the same session / cookie information and jwt token from the user_service. Basically i'm trying to have a single microservice that controls user authentication with jwt tokens so my react app can authenticate against the user service and use the token/ session for all downstream services. I have three services: user_service - contains all the user information and sets the authenticated session friend_service - uses user_service session and jwt for authentication tracking_service - uses user_service session and jwt token for authentication The Problem: The downstream services even via the Django Rest Framework UI the session isn't shared. What I've Discovered: Redis has the session token: :1:django.contrib.sessions.cached3bq2jfv2r88hcdqezlfmgng1hbyauzf The web browser cookie for webapp is set to: 3bq2jfv2r88hcdqezlfmgng1hbyauzf The settings files, and Django secret key are identical between the services This was working originally with just one downstream microservice but when I added the second microservice tracking_service it stopped working for all microservices. Everything I've read says you just have to make sure the cache setup is correct. Which I've done redis is getting the information but the …