Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
crypto confirmation using django
hey im creating a website where users need to send thir crypto namely usdt or worldcoin, im having trouble knowing who and what amount has been sent so that i can realise products, please help this is me trying to fetch prices using api sync def home(request): # Fetch Worldcoin (WLD) and USD prices from CoinGecko API asynchronously wld_price, usd_price = await asyncio.gather(fetch_price('worldcoin'), fetch_price('usd')) return render(request, 'index.html', {'wld_price': wld_price, 'usd_price': usd_price}) async def fetch_price(currency): api_url = f'https://api.coingecko.com/api/v3/simple/price?ids={currency}&vs_currencies=usd&x_cg_demo_api_key=CG-vQnfgGR63qMZ2LVVJfLJ2Wj2' response = await asyncio.to_thread(lambda: requests.get(api_url)) data = response.json() return data[currency]['usd'] -
Not seeing my view at api/docs. Not sure if its the url or the request im trying itself
The idea is to make POST, GET and DELETE requests for photos. When I try regestering the url at URL pattern nothing is showing yet im also not getting any errors. I feel like this should be a fairly easy fix no? views.py class GroundsDrivewayPhotosViewSet(APIView): """Manage comments in the database.""" serializer_class = serializers.GroundsDrivewayPhotosSerializer queryset = GroundsDrivewayPhotos.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @api_view(['POST', 'GET', 'DELETE']) def upload_grounds_driveway_photo(self, request, pk=None): """Upload an image to report.""" report = self.get_object() serializer = self.get_serializer(report, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get_queryset(self): """Filter queryset to authenticated user.""" return self.queryset.filter(user=self.request.user).order_by( 'grounds_driveway_photos') urls.py app_name = 'report' urlpatterns = [ path('photos/grounds-driveway-photos', views.GroundsDrivewayPhotosViewSet.as_view(), name="grounds-driveway-photos") ] -
Creating Custom Filter in Django Admin with JavaScript Flatpickr
I am currently working on a project where I have successfully integrated Flatpickr calendar into my Django admin view. The calendar allows users to select a date, and I want to extend this functionality by creating a custom filter. Essentially, I want to replicate the behavior of a Django-filter, but with my custom calendar. Could anyone provide guidance on how I can achieve this? Are there any existing examples or resources that demonstrate the integration of a custom JavaScript calendar with Django admin filters? I already tried with Custom filters but I can not achieve the functionality that iam looking for Thank you -
How do I configure Django / Nginx to serve later-created Media files?
In my views.py, I have a function that creates a .wav file (speech synthesis of user-created input). This file is then stored in my media folder: (views.py): filepath = synthesize_speech(text, language) if filepath: # Provide a URL to access the audio file audio_url = request.build_absolute_uri(settings.MEDIA_URL + filepath) return JsonResponse({'audio_url': audio_url}) (settings.py): MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This works together with (urls.py) really well in DEBUG: urlpatterns = [ # other URL patterns... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But in production, using Nginx, this does not work anymore. My Nginx config looks like this (nginx.conf): server { listen 80; location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /static/ { alias /usr/src/app/staticfiles/; } location /media/ { alias /usr/src/app/media/; } } Also, I have added a volume (docker-compose.yml): version: '3' services: ... nginx: build: ./nginx ports: - "80:80" volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media depends_on: - web redis: image: "redis:alpine" volumes: static_volume: media_volume: (Please note, I have read, that it is not ideal to have the media folder within the Django project, but that is for now the easiest way for me to switch between dev and prod). I … -
Django admin login only works with superusers created from shell
i have a custom user using AbstractUser just to add timestamps and a fk to it from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings from .managers import CustomUserManager class SubUser(AbstractUser): if settings.DEBUG: parent_user_id = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True) else: parent_user_id = models.ForeignKey('self', on_delete=models.RESTRICT, null=True, blank=True) # Timestamps created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "username" objects = CustomUserManager() def __str__(self): return self.username I read that to encrypt passwords well I must create a manager: from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, username, password=None, **extra_fields): user = self.model(username=username, **extra_fields) print(username) print(password) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password=None, **extra_fields): user = self.create_user(username, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user when i create a superuser from shell: u = SubUser.objects.create_superuser(username='asd', password='asdasd') the instance creates successfully, the password is encrypted and my login in admin/ with that superuser works but if i create a normal user: u = SubUser.objects.create_user(username='qwe', password='qweqwe') the instance creates successfully, the password is encrypted and BUT my login in admin/ DOESNT work now, also i read that if I use a custom user i should use my manager, in the shell i did: user_manager = CustomUserManager() new_user = … -
Image attribute of an object not working in django
I am looping through each object and image attribute of the objects dont appear on the website. is the attribute of the objects home.html file I want to see the photos of each object with for loop on my website I did all the necessary changes in settings.py -
How to manage the increase in memory consumption of redis-server in a Docker environment?
I am using the redis-server as part of a Docker stack in a Django project that uses Celery Beat for scheduled tasks. While monitoring the processes with the htop command, I noticed that the memory used by the redis-server progressively increases over time. The increase in memory seems to be gradual and continuous. Are there recommended practices or settings that I should implement to manage the memory used by the redis-server, especially in an environment with Celery Beat?" Docker version 24.0.7 Docker Compose version v2.21.0 local.yml redis: image: redis:6 container_name: scielo_core_local_redis ports: - "6399:6379" celeryworker: <<: *django image: scielo_core_local_celeryworker container_name: scielo_core_local_celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: scielo_core_local_celerybeat container_name: scielo_core_local_celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat base.py # Celery # ------------------------------------------------------------------------------ if USE_TZ: # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-timezone CELERY_TIMEZONE = TIME_ZONE # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-broker_url CELERY_BROKER_URL = env("CELERY_BROKER_URL") # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_backend CELERY_RESULT_BACKEND = CELERY_BROKER_URL # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content CELERY_ACCEPT_CONTENT = ["json"] # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer CELERY_TASK_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer CELERY_RESULT_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-time-limit # TODO: set to whatever value is adequate in your circumstances CELERY_TASK_TIME_LIMIT = 5 * 60 # http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-soft-time-limit # TODO: set to whatever value is adequate in your circumstances CELERY_TASK_SOFT_TIME_LIMIT = … -
Django doesn't recognise column added using RunSQL Migration
I am trying to add a SERIAL non-primary column to an existing table. Django does not seem to have support for this (AutoField must be primary, and I cannot make this field primary). However postgres does support SERIAL columns, so in the generated migration file I can add the following operation: class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.RunSQL( sql="ALTER TABLE portal_referral ADD referral_id SERIAL;", reverse_sql="ALTER TABLE portal_referral DROP referral_id;" ) ] however, it does not appear that Django 'registers' the effects of this migration. That is to say, when running manage.py makemigrations again, the tool will attempt to add referral_id again in a new migration. The model is defined as class Referral(utils.UUIDPrimaryKeyBase, utils.TimeStampedModel): data = models.JSONField(encoder=DjangoJSONEncoder) supplier = models.ForeignKey(Supplier, blank=True, null=True, on_delete=models.PROTECT, related_name="referrals") session_id = models.UUIDField(editable=False, blank=True, null=True, unique=True) referral_id = models.IntegerField() def __str__(self): return f"<referral id={self.id} supplier={self.supplier}>" I did find a way to work around this, where after letting the migration generate its code I can insert some overriding SQL statements afterwards. class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.AddField( model_name='referral', name='referral_id', field=models.IntegerField(default=0), preserve_default=False, ), migrations.RunSQL( sql="ALTER TABLE portal_referral DROP referral_id;", reverse_sql="ALTER TABLE portal_referral ADD referral_id INT DEFAULT 0;" ), migrations.RunSQL( sql="ALTER … -
TypeError: SearchProduct.get() got an unexpected keyword argument 'query'
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE and PyCharm Community Edition 2023.2 and djangorestframework==3.14.0 and Django==4.2.4 and djangorestframework-simplejwt==5.3.0. question : Actually, I don't know how to send this query parameter to Django's base class view that inherits from GenericAPIView , how solve this error ? BACKEND: Consider - product_views.py : class SearchProduct(GenericAPIView): serializer_class = ProductSerializer pagination_class = CustomPagination1 def get_queryset(self, *args, **kwargs): # the lead id query = self.request.GET.get("query") # this filter base on the lead id provided lookup = Q(name__icontains=query) | Q(description__icontains=query) | Q(producttag__title__icontains=query) products = Product.objects.filter(lookup).distinct() return products def get(self, request): page = self.paginate_queryset(self.get_queryset()) if page is not None: serializer = self.get_serializer(page, many=True) result = self.get_paginated_response(serializer.data) data = result.data # pagination data else: serializer = self.get_serializer(queryset, many=True) data = serializer.data payload = { 'return_code': '0000', 'return_message': 'Success', 'data': data } return Response(data , status=status.HTTP_200_OK) Consider - product_urls.py: path('search_product/<str:query>/' , views.SearchProduct.as_view() , name="search_product"), FRONTEND: Consider - productAction.py: export const productsSearchAction = (query , pageNumber) => async (dispatch , getState) => { try { dispatch({type: PRODUCTS_SEARCH_REQUEST}); const {data} = await axios.get(`http://127.0.0.1:8000/api/v1/products/search_product/${query}/?page=${pageNumber}`); dispatch({type: PRODUCTS_SEARCH_SUCCESS , payload: data}); localStorage.setItem("productsSearch" , JSON.stringify(data)); } catch (error) { dispatch({ // PRODUCTS … -
why volumes not working correctly in docker whene i try to dockerize django app?
The issue arises when I attempt to proceed without using volumes; everything works correctly. However, when volumes are included, I get the following error: django_app | python: can't open file '/app/manage.py': [Errno 2] No such file or directory docker-compose : version: '3.8' services: app: build: . volumes: - ./django:/app // the problem is here ports: - "8000:8000" image: app:django container_name: django_app command: python manage.py runserver 0.0.0.0:8000 dockerfile : FROM python:3.12.1-slim ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . -
didn't redirect to next parameter? django
my authentication view: class LoginView(auth_views.LoginView): form_class = LoginForm template_name = 'event/login.html' def post(self, request, *args, **kwargs): next_url = self.request.POST.get('next', reverse('event:create_table')) response = super().post(request, *args, **kwargs) redirect_url = reverse('event:login') + f"?next={next_url}" #ログインできたら、前の画面・ホーム画面に戻る if self.request.user.is_authenticated: return redirect(next_url) else: return redirect(redirect_url) return response class RegisterView(generic.CreateView): form_class = RegisterForm template_name = 'event/register.html' #登録できたら、前の画面・ホーム画面に戻る def form_invalid(self, form): messages.error(self.request, '会員登録に失敗しました。正しい情報を入力してください。') next_url = self.request.GET.get('next', reverse('event:create_table')) return redirect(next_url) def get_success_url(self): messages.success(self.request, '会員登録完了!ログインしてください') next_url = self.request.GET.get('next', reverse('event:create_table')) return next_url my login html: <h1>ログイン</h1> <form action="{% url 'event:login' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="next" value="{{ request.GET.next }}"> <!-- ログインボタン --> <button type="submit" class="submit-button" id="submit">ログイン</button> </form> My problem was it didn't redirect to the previous page after login. It worked before this but suddenly it didn't. The url included the previous url in the next parameter but after submitting the form, it redirect to the default event:create_table. Can someone give me any idea why did this happen?? i tried changing to request.POST.get('next', reverse('event:create_table')) and it kinda seems to work, but previously i use request.POST it didn't work so now I am confused. And in my test case, request.POST didnt redirect to the correct url but request.GET did so I don't know my django website couldn't work … -
How can I reset the username in Django if I mistakenly set it wrong?
Is it possible to reset the superusername in Django if it was mistakenly set incorrectly? I made an error during the initial setup and need guidance on how to rectify it. What steps can be taken to change or reset the username in Django to ensure accuracy and consistency with the intended information? I want the solution for reset the superusername n in Django -
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 …