Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Looking for Inspiration & Recommendations for My Upcoming POS Project using Django [closed]
👋 I'm planning to build a Point of Sale (POS) system using Django, and I’m looking for recommendations and inspiration. I want to make it efficient, user-friendly, and scalable. Are there any open-source POS projects in Django that you'd recommend for reference? -
In django transactions, what happens if an error is raised in on_commit?
Situation I have a postgres database, and I'm using django transaction's on_commit hook to do something (in this case move a file but it doesn't really matter what for the purposes of the question) once the save of a model has been committed to the database. from django.db import models, transaction def my_oncommit_callback(): # Do something on commit raise ValueError("what if I raise an error") class MyModel(models.Model): def save(self, *args, **kwwargs): transaction.on_commit(my_oncommit_callback) super().save(*args, **kwargs) The Question If my_oncommit_callback raises an error, is the transaction rolled back, or will I get a broken state because my on_commit function hasn't worked as expected? -
pytest_django model class attribute not filled for __init_subclass__
I have a specific problem. class A: SOME_ATTR: int def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) attr = getattr(cls, "SOME_ATTR", None) if not attr: raise TypeError(f"Class '{cls.__name__}' must define 'SOME_ATTR'") classB(models.Model, A): SOME_ATTR = 0 In this case everything works as expected but pytest tests. pytest_django creates: cls = <class 'fake.B'> which has no attribute 'SOME_ATTR' Is there any option to enforce it? I'v tried to add a session scope autouse fixture but it didn't work as it happens before it. -
How to Structure a Django Project for a Multi-questuinnaire System and Import Questions in Bulk?
I'm building a Django project that will host dozens of questionnaires. I have a few architectural and implementation questions: 1)Should I create a separate app for questionnaires and another app for test takers within the main Django projectand put models like User _Answer and Test_Result within the test takers app itself? 2)In the test model, how can I design the database structure to handle different question types? Some questions are only text-based, some are only image-based, and some contain both text and images. 3)Since each test may contain hundreds of questions, manually entering them via the Django admin panel is impractical. Is there a way to bulk import questions from a Word document? I appreciate any insights or best practices for handling these challenges in Django. -
Django TypeError: 'Category' object is not iterable in template loop
1️⃣ Problem Description: I'm working on a Django project where I'm trying to display a category and its associated products. However, I'm getting the following error in my template: 2️⃣ Error Message: TypeError at /category/2/'Category' object is not iterableRequest Method: GETRequest URL: http://127.0.0.1:8000/category/2/Django Version: 5.1.4Exception Type: TypeErrorException Value: 'Category' object is not iterableException Location: C:\Users\brahm\OneDrive\Desktop\Django\one\Lib\site-packages\django\template\defaulttags.py, line 198, in renderRaised during: accounts.views.categoryPython Executable: C:\Users\brahm\OneDrive\Desktop\Django\one\Scripts\python.exePython Version: 3.11.5Python Path: ['C:\Users\brahm\OneDrive\Desktop\Django\one\Scripts\user_authincation','C:\Program Files\Python311\python311.zip','C:\Program Files\Python311\DLLs','C:\Program Files\Python311\Lib','C:\Program Files\Python311','C:\Users\brahm\OneDrive\Desktop\Django\one','C:\Users\brahm\OneDrive\Desktop\Django\one\Lib\site-packages']Server time: Wed, 26 Feb 2025 06:25:55 +0000 3️⃣ My Django View (views.py): `def category(request,id): categories =Category.objects.get(id=id) products=Product.objects.filter(category=categories) context={ 'categories':categories, 'products':products, } return render(request,'category.html',context)` 4️⃣ My Django Template (category.html): {% for category in categories %} <a class="nav-link" href="/category/{{category.id}}/">{{category.name}}</a> {% endfor %} urls.py urlpatterns=[ #path('home',home,name='home'), #path('',register,name='register'), #path('login/',login_user,name='login'), #path('logout/',logout_user,name='logout'), path('category/<int:id>/',category,name='category'), ] models.py class Category(models.Model): name=models.CharField(default='uncategorized',max_length=100) is_active=models.BooleanField(default=True) def __str__(self): return self.name class Product(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='categories') product_name=models.CharField(max_length=120) img=models.ImageField(upload_to='photos/') created_date=models.DateTimeField(auto_now=True) desc=models.TextField() price=models.CharField(max_length=8) def __str__(self): return self.product_name 5️⃣ Expected Behavior: I want to display the category name and list of products under it. 6️⃣ Issue: Since category is a single object, it is not iterable, but my template uses {% for category in categories %}. 7️⃣ My Question: What is the correct way to access a single object in a Django template? Should I change my view … -
Django-storages inserting bucket name as a folder
I'm migrating to Django 5.1.6 (django-storages 1.14.5) from Django 3.2 using DigitalOcean S3-compatible Spaces and when I run python manage.py collectstatic the bucket name is being inserted as a folder when it used to not be. I want it to be stored in myBucket as /static/myFile.png, but it's being stored as /myBucket/static/myFile.png instead. In my settings.py file: STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "secret_key": "mySecretKey", "access_key": "myAccessKey", "bucket_name": 'myBucket', "endpoint_url": 'https://mySubdomain.sfo2.digitaloceanspaces.com/', "object_parameters": {'CacheControl': 'max-age=86400'}, "location": 'static', "default_acl": 'public-read', }, }, } STATIC_URL = "https://mySubdomain.sfo2.digitaloceanspaces.com/static/" Am I doing something wrong or is this a bug in the django-storages? -
How do I pass data from 2 datasets to a Django view?
I have a simple Django project that consists of 3 datasets: Members --< mem_ev >-- Events such that any Member can go to any number of events and any event can have many members (ie a classic many to many relationship). I have the members, events, members per event and events per member templates working but I want to pass a count of the number of events per member in the main members list (list.html). Given the following file structures how do I capture event_count per Member and how to I pass that to the relavant template (list.html)? My app:urls.py file is: app_name = 'wf' urlpatterns = [ path('',views.members_list,name='member-list'), path('home/',views.members_list,name='member-list'), path('events/',views.events_list,name='event-list'), path('about/',views.about,name='wf-about'), path('event_detail/<int:id>/',views.event_detail,name='event_detail'), path('list_event_members/<int:id>/', views.list_event_members, name='list_event_members'), path('list_member_events/<int:id>/', views.list_member_events, name='list_member_events'), ] My views.py file is: def members_list(request): members = Member.objects.all() event_count = ?? What goes here ?? <------ return render(request,'wf/list.html',{'members':members},{'event_count':event_count}) def events_list(request): events = Event.objects.all() return render(request,'wf/events.html',{'events':events}) def event_detail(request,id): event = Event.objects.get(id=id) return render(request,'wf/event_detail.html',{'event':event}) def about(request): return render(request,'wf/about.html') def list_event_members(request,id): event_members = Member.objects.filter(mem_ev__event_id=id) return render(request,'wf/list_event_members.html',{'event_members':event_members}) def list_member_events(request,id): member_events = Event.objects.filter(mem_ev__member_id=id) return render(request,'wf/list_member_events.html',{'member_events':member_events}) and the relvant template file (list.html) is: {% extends "wf/base.html" %} {% block content %} <h2>Members</h2> <table width="100%" cellpadding=8 style="border:1px solid black;"> <thead class="table-success"> <tr style="border:1px solid black;"> <th … -
django-ckeditor5 showing question mark instead of symbols
hi recently i switched to django-ckeditor5 and in the HTML code I'm using this - my_project/ │── manage.py │── my_project/ │── app/ │ │── models.py ... ... but after saving code it is displaying like this my_project/ ??? manage.py ??? my_project/ ??? app/ ? ??? models.py ... ... why │── is replaced by ?. in development server it is showing correctly but in production there is issue that is coming. -
rerro context_processors in django
dictionary update sequence element #0 has length 0; 2 is required I have a module called context_processors that when enabled does not appear on the login page and gives an error But when I disable it, the login page appears context_processors.py: import datetime from django.contrib.auth.decorators import login_required from permission.models import UserPermission from salemali.models import Salemali from term.models import Term from user.models import Branch @login_required def date_context_processor(request): if request.user.is_authenticated: current_datetime = datetime.datetime.now() term = Term.objects.filter(status=1).order_by('-datestart') salemali = Salemali.objects.all() branch = Branch.objects.all() user_permissions = UserPermission.objects.filter(user=request.user).values_list('permission__name', flat=True) return { 'current_day': current_datetime, 'terms': term, 'salemali': salemali, 'branch': branch, 'user_permissions': user_permissions } setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'dashboard.context_processors.date_context_processor', ], }, }, ] -
How can i get the id from request body in django
def index(request): form = Postform() if request.method == 'POST': template_string = request.POST.get("body") >! here i want the id for some reason print("Original", template_string) rendered_content = render_template_content(template_string) print("Rendered", rendered_content) form = Postform(request.POST) if form.is_valid(): post = form.save(commit=False) post.body = rendered_content post.save() form = Postform(initial={'body':rendered_content}) else: form=Postform() return render(request, 'index.html', {"form": form}) I am using CKeditor in the frontend and is sending the whole text area in body {{product.name.1}} i want to extract this id -
How to limit google maps auto complete to only one country?
I have tried everything so my search input only gives autocomplete options from only Dominican Republic but I have not been able to achieve it, anyone here knows how to do this? <input type="text" id="searchInput" class="form-control" placeholder="Search for a location..." > let autocomplete; const input = document.getElementById('searchInput'); autocomplete = new google.maps.places.Autocomplete(input, { types: ['(cities)', 'geocode'], // Allow both city and address searches componentRestrictions: { country: 'do' } }); // Handle place selection autocomplete.addListener('place_changed', function() { const place = autocomplete.getPlace(); if (!place.geometry) { return; } -
django app: how to read a bit of html in javascript
I have a django app that has an design issue I'd like to fix: a script wants to inject a piece of html that contain django tags. What we have now works, but has some unfortunate aspects: Save the script as an html snippet that is nothing but a script: the first line is <script> and the last line closes that script. Pages which use this script import it just like any html snippet. This script sets a local variable to the html bit, as a long string, then finds where the html bit is wanted, and calls insertAdjacentHTML to insert it. So the snippet is an html file that contains nothing but a script, and that script in turn contains hard-coded html as a string. This is confusing to read and prevents our javascript and html linters from working on this snippet. But the code works, and the script can be used by any page by simply importing the one snippet. Is there a cleaner solution? My ideal solution would: Store the html bit in an html file. Store the script in a .js file. Allow pages that use the script to just load the script. I have tried … -
Why isn't the create method in my custom manager working?
I'm trying to create a custom manager for a model class in my Django project. The model classes Story and Plot have a one-to-one relationship. I want a new Plot instance to be automatically created when a new Story instance is created. Right now I do this through the view function, but it fails when testing Story object creation without the view function. I know there are a few ways to accomplish this, but I've decided to use a custom manager to add this post-creation logic by overriding the objects.create method. The relevant code is below: class Story(models.Model): ... other fields objects = models.Manager() class Plot(models.Model): ... other fields story = models.OneToOneField(Story, on_delete=models.CASCADE, null=True, default=None, related_name='plot') class StoryManager(models.Manager): def create(self, **kwargs): story = super().create(**kwargs) plot = Plot.objects.create( ... other kwargs, story_id=story.id ) return story # Assign the story manager to the Story model Story.objects = StoryManager() Now I'm getting the following traceback while running tests that use the Story.objects.create method: File "C:\Users\jacob\documents\programming\story-builder\storybuilder\app\models.py", line 221, in create story = super().create(**kwargs) File "C:\Users\jacob\documents\programming\story-builder\.venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ File "C:\Users\jacob\documents\programming\story-builder\.venv\Lib\site-packages\django\db\models\query.py", line 669, in create self.model._meta._reverse_one_to_one_field_names ^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute '_meta' I'm new to the concept … -
Read data json in django
I am currently working on a project where users will be able to authenticate themselves thanks to a form that I protected with a csrf token, but for now I only take care of the server side party, here is the code: @api_view(['POST']) @csrf_protect @permission_classes([AllowAny]) def login(request): if request.method != "POST": return JsonResponse({"error": "Seules les requêtes POST sont autorisées."}, status=status.HTTP_405_METHOD_NOT_ALLOWED) try: # Lecture sécurisée des données data = json.loads(request.body) username = data.get("username") password = data.get("password") if not username or not password: return JsonResponse({"error": "Nom d'utilisateur et mot de passe sont requis."}, status=status.HTTP_400_BAD_REQUEST) # Recherche de l'utilisateur dans les deux tables user = None role = None try: user = Administrateur.objects.get(username=username) role = "admin" except Administrateur.DoesNotExist: pass if not user: try: user = Employes.objects.get(username=username) role = "employe" except Employes.DoesNotExist: pass if not user or not check_password(password, user.password): return JsonResponse({"error": "Identifiants incorrects."}, status=status.HTTP_401_UNAUTHORIZED) # Génération des tokens refresh = RefreshToken.for_user(user) # Réponse sécurisée response = JsonResponse({"username": user.username}) # Stocker le JWT dans un cookie HttpOnly sécurisé response.set_cookie( key='access_token', value=str(refresh.access_token), httponly=True, secure=True, samesite='Strict', max_age=3600 ) # Stocker le rôle pour le frontend response.set_cookie( key='user_role', value=role, httponly=False, secure=True, samesite='Strict', max_age=3600 ) return response except Exception as e: return JsonResponse({"error": f"Erreur inattendue : {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) … -
Why I am getting htmx:targetError when calling form.requestSubmit?
I am using htmx to load some content when openning an accordion in my django template. I initially include the cover card partial template and when I close the accordion I remove the whole partial template. Then whenever the accordion opens I dispatch a custom event to trigger the htmx swap and return the same partial template in the response. The code looks like this initially: ... <details open id="cover-card-section" hx-get="{% url 'update-cover-card' object.id %}" hx-swap="outerHTML" hx-target="#temp-cover-card-form" hx-trigger="open-cover-card-section"> <summary > Cover Card </summary> {% include "path/to/cover_card.html" %} {% comment %} Element to be replaced by actual cover card form {% endcomment %} <div id="temp-cover-card-form" style="display: none; align-items: center; justify-content: center; width: 100%; height: 200px;"> <svg width="40" height="40" stroke="rgba(0, 0, 0, 0.5)" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_V8m1{transform-origin:center;animation:spinner_zKoa 2s linear infinite}.spinner_V8m1 circle{stroke-linecap:round;animation:spinner_YpZS 1.5s ease-in-out infinite}@keyframes spinner_zKoa{100%{transform:rotate(360deg)}}@keyframes spinner_YpZS{0%{stroke-dasharray:0 150;stroke-dashoffset:0}47.5%{stroke-dasharray:42 150;stroke-dashoffset:-16}95%,100%{stroke-dasharray:42 150;stroke-dashoffset:-59}}</style><g class="spinner_V8m1"><circle cx="12" cy="12" r="9.5" fill="none" stroke-width="3"></circle></g></svg> </div> </details> ... The cover card partial template looks like this: <div class="container" id="cover-card-form-container" style="max-width:700px;" puny-settings> <style> ... </style> <div> <form id='image-upload-form' hx-swap="none" hx-encoding='multipart/form-data' hx-post='/en/home/upload-card-image/'> {% csrf_token %} {{ form.image.errors }} {{ form.image.label_tag }} {{ form.image }} <div style="display: none; width: 100%; align-items: center; gap: 8px; margin-bottom: var(--pico-spacing)" id="progress-container"> <progress style="width: 50%; margin-bottom: 0" id="progress-bar" value="0" … -
How to make the function stop immediately, when in websocket stop requested?
I want to stop running the generating function immediately, whenever stop_requested in the websocket. class ImageGeneration(BaseAIGeneration): async def process(self, websocket, prompt): if websocket.stop_requested: return None await super().process(websocket, prompt) if websocket.stop_requested: return None response = await self.generate_image(prompt=prompt, model=self.model, size=size) if websocket_instance.stop_requested or not response: return None if response and isinstance(response, list): image_url = response[0].url return image_url And generate_image function currently is synchronous function async def generate_image( prompt: str, model: str, size: str = "1024x1024" ): response = await client.images.generate( model=model, prompt=prompt, size=size, n=1 ) return response.data Currently it waits until generate_image fully runs, and only then stops. I was thinking of creating a task, that will gonna check if the response: while not task.done(): if websocket_instance.stop_requested: task.cancel() await asyncio.sleep(0.1) But for me this solution looks weird, and I do not think it is the correct way, how to make the function stop immediately, when in websocket stop requested? -
Deploying Django API with Render keeps loging 400 bad request
I am trying to host my Django API with renders free tier I have specified all the env variables including renders domain in allowed origins but I still get 400 Bad Request responses from renders logs. logs: 127.0.0.1 - - [24/Feb/2025:22:47:56 +0300] "HEAD / HTTP/1.1" 400 143 "-" "Go-http-client/1.1" ==> Your service is live 🎉 127.0.0.1 - - [24/Feb/2025:22:48:09 +0300] "GET / HTTP/1.1" 400 143 "-" "Go-http-client/2.0" my settings.py ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") CSRF_TRUSTED_ORIGINS = env.list("TRUSTED_ORIGINS") CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS") all env variables are supplied on renders environment tab but it still fails -
Django/Celery SQLite database locked on concurrent access
I have a local Django 5.1/Celery 5.4 project that is using SQLite. I am the only user. Certain model saves trigger a Celery task that queries (SELECT) for the updated record (using the Django ORM), then runs an API call to update a remote record based on the local data, and then runs another UPDATE locally. The task wraps all this inside of with transaction.atomic():. (The Celery worker is configured to run tasks in serial.) While this task is running, any attempts to write to the database result in a "database is locked" OperationalError. I have configured Django/SQLite with the latest "production-ready" settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_DIR / 'db.sqlite3', 'OPTIONS': { 'init_command': """ PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout = 5000; PRAGMA temp_store = MEMORY; PRAGMA mmap_size=134217728; PRAGMA journal_size_limit=67108864; PRAGMA cache_size=2000; """, 'transaction_mode': 'IMMEDIATE', 'timeout': 20, }, }, } I was under the impression that with these settings, concurrent access was possible. "SQLite in Production" is the latest hotness, and these settings, especially the new-to-Django 5.1 'transaction_mode': 'IMMEDIATE' in OPTIONS, would allow writes to queue. What am I missing? -
dynamically instantiate database django
In a django web application, when logging in I am saving the name of the database in the session. I need a method to dynamically instantiate the database using this name that is saved in the user session. I dont't want to use "using()" because my aplication is already done, and it would give me a lot of work, neither by configuring multiple databases in your settings (because my databases are being createded dinamically) if there is another way i would like to know. Maybe it's not possible, i understand if it's the case... I tried middlewares, routes, threading, decorators but maybe a think i would have done something wrong. I exhausted my attempts. As far as I could go i get logged in the right database until the second screen of my application, when i am browsing in the application the 3 screen i pass the database goes back to default. middleware: import re from django.utils.deprecation import MiddlewareMixin from django.db import connections from .thread import set_banco_academia class DatabaseMiddleware(MiddlewareMixin): def process_request(self, request): """ Middleware que define dinamicamente o banco de dados a ser usado com base na sessão do usuário e adiciona a conexão ao Django. """ if not hasattr(request, … -
Django form doesn`t appear in page
I want to add posts in adding system from user profile page (without creating another page to adding). To profile page including html file for creating post I created model, form, view and html but have no idea why it isn`t working. The form doesn`t appear in page (except bottom "publish") include is working forms from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class Meta: model = Post fields = ['text', 'photo', 'video'] views from django.shortcuts import redirect, render from .models import Post, Comment from .forms import PostForm, CommentForm # Create your views here. from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_GET, require_POST @login_required(login_url='users:login') def create_post(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('user:profile') else: form = PostForm() context = {'form': form} return render(request, 'post/create_post.html', context) create_post.html <div class="posts-section"> <div class="new-post"> <form method='post' enctype="multipart/form-data"> {{form.as_p}} {% csrf_token %} <button>Publish</button> </form> </div> </div> user_profile.html {% extends "base.html" %} {% load profile_tags %} {% block content %} </div> <div class="profile-info"> <p><strong>Email:</strong> {{ user.email }} </p> <p><strong>About:</strong>{{ profile.about }}</p> </div> {% include "post/create_post.html" %} </div> {% endblock content %} -
Is there any way to take add tooltip to the select2 li items?
i work on a django project where i also use bootstrap and select2. I have this HTML: {% load i18n %} <select id="{{ select_id }}" name="{{ select_name }}" class="form-control"> <option value="">{% trans 'Alege TVA' %}</option> {% for vat_rate in vat_rates %} {{ vat_rate.text_tooltip }} <option value="{{ vat_rate.actual_value }}" title="{{ vat_rate.text_tooltip }}"> {{ vat_rate.full_name }} </option> {% endfor %} </select> and this in JavaScript: $('#id_vat_value').select2({ placeholder: gettext("Alege TVA"), escapeMarkup: function (m) { return m; }, matcher: function (params, data) { return TrimSpacesSelect2(params, data); }, }) is there any way to add the tooltip to the select2 li items? I tried to add it in select2:open, but i don't think is really good, right now it is showing the tooltip but i don't know if it's the best choice. .on('select2:open', function () { setTimeout(function () { $('.select2-results__option').each(function () { var $option = $(this); var optionId = $option.attr('id'); var originalOption = $('#id_vat_value option').filter(function () { return $(this).val() === optionId.split('-').pop(); }); var tooltip = originalOption.attr('data-original-title'); if (tooltip) { $option.attr('title', tooltip); $option.attr('data-toggle', 'tooltip'); } }); $('[data-toggle="tooltip"]').tooltip({ delay: {show: 500, hide: 0}, trigger: "hover" }); }, 100); }); -
Where to deploy Next.js & Django
I have created a project that uses Next.js on the frontend and Django on the backend, the web app uses JWT for requests. Now I want to deploy the project and want to ask where I should do it? Do I have to use two different services or can I use one service for both? I have done the Next.js getting started tutorial where you get to create a dashboard app and deploy it using Vercel, that was very simple, can I do the same with this project? Also, I'd like to add that the database used currently while I'm developing is the default SQLite but I do want to switch to a "real" database like PostgreSQL, for example, later when launching. -
Django Celery: Kombu connection refused error
It seems a bit odd, maybe I'm missing something, but whenever I send tasks to celery queue it suddenly gives error: AttributeError: 'ChannelPromise' object has no attribute 'value' It works at first but if tasks are sent to the queue at a slightly higher frequency, it suddenly starts to give the above error. Looks like some kind of blocked process or something like that. Broker is aws sqs Celery settings: CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'sqs://' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region' : 'us-south-1', #temp name 'visibility-timeout' : 3600, 'polling-interval' : 10 } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' Packages: celery = ">=5.0.5" django = "==4.2.16" kombu = "==5.4.2" django-celery-beat = ">=2.0.0" django-celery-results = ">=2.2.0" Files: project/init.py from .celery import app as celery_app __all__ = ['celery_app'] project/celery.py import os from celery import Celery from project.settings import settings # set the default Django settings module for the 'celery' program. #settings are kept inside a separate folder for multiple envs [project/settings/settings_prod.py,project/settings/settings_stag.py,project/settings/settings.py] os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): pass Complete error trace: kombu.exceptions.OperationalError: [Errno 111] Connection refused on next try in production. complete … -
How to secure JWT tokens with a DRF backend supporting both mobile and SPA clients?
I am developing an application that uses the Django REST Framework to provide a REST API. I intend to protect it using token authentication, with the help of simple_jwt. Example API overview: /auth/login/: Supports POST, requires valid username and password, returns a JWT access and refresh /auth/refresh/: Supports POST, requires a valid refresh token, returns new access and refresh tokens /protected/endpoint/: Requires a valid access token From reading on CSRF I have gathered: CSRF is only needed if cookies are involved, so only use for the SPA client To persist the JWT token: SPA: Persist in an httpOnly cookie with secure=true and same-origin set App: Persist in however the app persistent state works So far so good, however, this would mean that my REST API needs to both require CSRF tokens for requests coming from the SPA and not require/ignore CSRF tokens for requests coming from mobile app clients. Since this is logically impossible I was first thinking of implementing 2 separate APIs. I.e.: /spa/auth/..., /spa/protected/...: For SPA clients, where all endpoints require a CSRF token /mobile/auth/..., /mobile/protected/...: For mobile clients, where all endpoints are CSRF exempt. But doing this just means that my CSRF protection is useless, since a … -
How to fetch real-time google cloud run job logs?
I am building a CI/CD kind of tool which is actually a web app. The stack is django-rest-framework on the backend and React (Vite) on the frontend. Currently the pipeline running and the actions from the stages that are running are all working, the jobs are being created, ran, deleted and it all works fine. This is all happening through the Google Cloud Run Jobs. For the app to make sense, I need to be able to get real-time logs from that specific job while it is running. Currently I have a crude temporary implementation where I am using the Google Cloud Logging API with filters to periodically get the logs for that job. This is the mentioned crude implementation: from google.cloud import logging_v2 from apps.docker_app.utils.google_credentials import get_google_credentials def _stream_job_logs(logging_client, log_filter): seen_entries = set() while True: entries = logging_client.list_entries(filter_=log_filter) for entry in entries: if entry.insert_id not in seen_entries: seen_entries.add(entry.insert_id) yield entry time.sleep(1) class GoogleLogsClient: def __init__(self): storage_credentials = get_google_credentials() self.client = logging_v2.Client(credentials=storage_credentials) def stream_job_logs(self, log_filter): for entry in _stream_job_logs( logging_client=self.client, log_filter=log_filter ): if "All stages completed successfully" in entry.payload: break timestamp = entry.timestamp.isoformat() print("* {}: {}".format(timestamp, entry.payload)) While this does work, I am limited to 60 read requests to the …