Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden Error (403) in Django Test Cases on GitHub Actions
I have a Django REST framework API application hosted on AWS ECS, using RDS. I am working on implementing CI/CD using GitHub Actions, where we need to include a test suite. The corresponding CI/CD implementation is as follows: unit-tests: runs-on: ubuntu-latest environment: ${{ inputs.build_env }} env: ENVIRON: ${{ secrets.ENVIRON }} PG_DB_NAME: ${{ secrets.POSTGRES_DB }} PG_DB_USER: ${{ secrets.POSTGRES_USER }} PG_DB_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} PG_DB_HOST: ${{ secrets.POSTGRES_HOST }} PG_DB_PORT: ${{ secrets.POSTGRES_PORT }} SECRET_KEY: ${{ secrets.SECRET_KEY }} steps: - name: Checkout repo uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v2 with: python-version: ${{ env.PYTHON_VERSION }} - name: Install dependencies run: | python3 -m pip install --upgrade -r requirements.txt - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ secrets.AWS_REGION }} - name: Run tests run: | cd ./dbasebe python3 manage.py test cd .. And the unit test case is class TestFirstEndpoint(SimpleTestCase): def setUp(self): self.client = APIClient(enforce_csrf_checks=False) def test_endpoint_no_valid_user(self): url = reverse('myapp:firstendpoint') response = self.client.post(url, {'userid':'testuser'}, format='json') `self.assertEqual(response.status_code, 404) the corresponding endpoint view is @api_view(["POST"]) @authentication_classes( ([utils_security.CsrfExemptSessionAuthentication, BasicAuthentication]) def first_endpoint_view(request): userid = request.data.get("userid", 'USER1') user = Mymodel.objects.filter(userid=userid) if user.exists(): # do my job return Response({"message": "Work is done"}, status=status.HTTP_200_OK) else: return Response({"message": "User not found"}, status=status.HTTP_404_NOT_FOUND) … -
'<' not supported between instances of 'NoneType' and 'int' django views.py
templates/html {% if guess == rand_num %} <h1>{{message1}}</h1> {% elif guess > rand_num %} <h1>{{message3_a}}</h1> <h1>{{message3_b}}</h1> {% elif guess < rand_num %} <h1>{{message2_a}}</h1> <h1>{{message2_b}}</h1> {% endif %} views.py def easy(request, ): rand_num = random.choice(lst) print(rand_num) attempts = 11 for _ in range(0, 10): # print(f"You have {attempts} remaining to guess the number.") # guess = int(input("Make a guess: ")) guess = request.GET.get('guessed_number') if guess == rand_num: return render(request, 'easy.html', {'attempts': attempts, "message1": f"You got it! The anshwer was {rand_num}"}) break elif guess < rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message2_a": "Too Low", "message2_b": "Guess again"}) elif guess > rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message3_a": "Too High", "message2_b": "Guess again"}) attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, 'guess': guess, 'rand_num': rand_num}) return render(request, 'easy.html') i Am triying to Run this Django code. but it is not running.. -
In Django 5.1 difference between Model and AbstractUser
I am looking at the Django Documentation and am a bit confused as the differences between: from django.contrib.auth.models import AbstractUser from django.db.models import Model I tried doing the following in a class and got an error that has to do with the following topic: Python multiple inheritance and MRO The error emerged because I had done the following: class Employee(Model, AbstractUser): pass When I went to make migrations in Django, an error message said it violated MRO. When I searched what that meant on Google, I found a Stack Overflow post that mentions that it happens when it can't decide between the two classes, a specific value, or a method. In my research, there might be a conflict amongst similar methods in class. I am expecting to have an Employee that has a custom authentication, and is an entity in the database. How would I go about achieving this, do I have to pick AbstractUser over Model? -
Unable to connect via saml sso login to Azure AD
I am using django as backend and I am trying to do saml sso login for Azure AD. I am getting below error for xmlsec. I am using djangosaml2, pysaml2 in django backend for saml auth error=Error: xmlSecCryptoAppKeyLoadEx failed: file=C:\Users\ADMINI~1\AppData\Local\Temp\2\tmpeq1v1od1.pemError: failed to load public key from "C:\Users\ADMINI~1\AppData\Local\Temp\2\tmpeq1v1od1.pem".Error: keys manager creation failed tmpeq1v1od1.pem file is created in Temp\2\ folder but when i try to run xmlsec signature verify command manually I am getting same error. -
django rest framework, how to override a field so that "null is zero"
Hello I have a Model with a field that is not null on the database -the field "amount". However on the api-level this field can be skipped, which should then be stored as the default value. I have tried several ways, however I keep coming back to the fact that to_internal_value() isn't executed for fields when the value is None? Even though the field has allow_null to be True? class NullIsZeroDecimalField(serializers.DecimalField): def __init__(self, **kwargs): super().__init__(allow_null=True, default=0, **kwargs) def to_internal_value(self, data: Primitive) -> Decimal: """Convert None or empty strings to 0 before validation. :param Primitive data: the input data return Decimal: decimal value """ print('internal value') if data is None or data == "": return Decimal(0) return super().to_internal_value(data) class ModelWithAmountSerializer(serializers.ModelSerializer): amount = NullIsZeroDecimalField(max_digits=20, decimal_places=10) class Meta: model = AmountModel fields = ("amount",) def test_serializer(self): serializer = ReceiptLineSerializer(data={"amount": None}) is_valid = serializer.is_valid() self.assertEqual(serializer.validated_data["amount"], Decimal(0)) However here the assertion fails. And upon research it turns out that the "to_internal_value" is never called for "none" fields. it is just short-circuited. How to overcome this? And if possible, could I instead of defaulting to "0" default to the "default-of-the-model-definition"? IE as if the value is omitted when creating the model? -
Django Admin CSS Not Loading in Production Even Though Static Files Are Served (200 OK)
I'm experiencing an issue where my Django admin panel appears unstyled on my production server, even though all static files are being served correctly. The admin HTML includes proper <link> tags, and I can confirm that the CSS files are accessible via direct URL. Environment Details: Production: Azure VM Django: latest Application Server: Gunicorn Web Server: nginx on Ubuntu Middleware: Removed WhiteNoise (to avoid conflicts) Static Files: Collected using python manage.py collectstatic --noinput Note: I am using same azure VM for my django backend and react frontend What I’ve Done/Verified: 1. Django Settings: Set STATIC_URL and configured STATIC_ROOT STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 2. Nginx Configuration: server { listen 80 default_server; server_name _; client_max_body_size 200M; # Favicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/example/staticfiles/; autoindex on; } # Serve media files location /media/ { root /home/ubuntu/example; autoindex on; } # Proxy API requests to Django backend location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } # Proxy Django admin requests to the Django backend location /admin/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } # Serve the React frontend from its build output location / { root /home/ubuntu/frontend/dist; # Adjust path if needed try_files … -
django add success message erro
Whenever i am using messages I keep getting the same type error saying string is no callable. However this same code used to work, I am not sure what happened but it just stopped working and started giving me this error for all messages in all pages, even when i add something on admin panel. Not sure what is causing this error. Please help. Request Method: POST Request URL: http://127.0.0.1:8000/compras/fornecedores/ Django Version: 5.1.3 Exception Type: TypeError Exception Value: 'str' object is not callable Exception Location: /Users/macbook-fcorrea/Documents/Coding/cabiunas/compras/views/views.py, line 122, in fornecedores Raised during: compras.views.views.fornecedores Python Executable: /Users/macbook-fcorrea/Documents/Coding/cabiunas/cabiunas-env/bin/python3 Python Version: 3.13.1 Python Path: ['/Users/macbook-fcorrea/Documents/Coding/cabiunas', '/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python313.zip', '/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13', '/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/lib-dynload', '/Users/macbook-fcorrea/Documents/Coding/cabiunas/cabiunas-env/lib/python3.13/site-packages', '/Users/macbook-fcorrea/Documents/Coding/cabiunas/cabiunas-env/lib/python3.13/site-packages/setuptools/_vendor'] This is my views.py def fornecedores(request): form_empty = NewFornecedor() # FILTER fornecedor_filter = FornecedorFilter( request.GET, queryset=Fornecedor.objects.all().order_by('name')) all_forn = fornecedor_filter.qs if request.method == 'GET': context = { 'all_forn': all_forn, 'fornecedorform': form_empty, 'filter': fornecedor_filter.form } if request.htmx: return render(request, "compras/partials/fornecedor-lista.html", context) return render(request, "compras/fornecedores.html", context) elif request.method == 'POST': form = NewFornecedor(request.POST) if form.is_valid(): form.save() messages.success(request, 'Fornecedor adicionado com sucesso.') return redirect("compras:fornecedores") else: print(form.errors) return render(request, "compras/fornecedores.html", {'form': form, 'all_forn': all_forn, 'filter': fornecedor_filter.form}) This is my template: fornecedores.html {% extends "compras/layout.html" %} {% load crispy_forms_tags %} {% load static %} {% block body %} <div … -
Gmail API Not Sending Email Attachments with PDF in Django
I'm using the Gmail API to send emails with PDF attachments from my Django backend, but the attachment is not appearing in the email — only the email body is received. Here are the logs showing the PDF is generated and attached correctly: [DEBUG] Generated PDF size: 16988 bytes[DEBUG] Attaching PDF: invoice_EJ70FEX.pdf (size: 16988 bytes) [INFO] Email sent successfully. Message ID: 19561950e1b649a0 However, when I receive the email, no attachment is visible. Here's the email-sending code I'm using: from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from django.conf import settings from email.utils import formataddr import base64 logger = logging.getLogger(__name__) def send_damage_invoice(driver_data, pdf_content): """Send damage invoice email with PDF attachment.""" try: logger.debug("Preparing damage invoice email for %s (%s)", driver_data['name'], driver_data['vrm']) subject = f'Damage Charges Invoice - {driver_data["vrm"]}' from_email = formataddr(('H&S Autocare', settings.DEFAULT_FROM_EMAIL)) to_email = driver_data['email'] # Create context for email template context = { 'driver_name': driver_data['name'], 'vrm': driver_data['vrm'] } # Render email content html_content = render_to_string('emails/damage_invoice.html', context) text_content = strip_tags(html_content) # Create email message email = EmailMultiAlternatives( subject=subject, body=text_content, from_email=from_email, to=[to_email] ) email.attach_alternative(html_content, "text/html") # Attach PDF filename = f'invoice_{driver_data["vrm"]}.pdf' logger.debug("Attaching PDF: %s (size: %d bytes)", filename, len(pdf_content)) email.attach(filename, pdf_content, 'application/pdf') email.send(fail_silently=False) logger.info("Email sent successfully to %s", … -
Django Webhook Unauthorized Issue on Azure Despite Successful Local Testing
I have a Django + React project hosted on Azure. I'm using Azure Postgres as my database, and my webhook handler is set up to receive events from an external API (Seal Subscriptions). The webhook subscriptions/create event sends a POST request to my Django backend at: https://vitaverde-backend.greensky-92f80007.eastus.azurecontainerapps.io/shopify/webhook/subscription/ However, I keep getting the following error in my Azure backend log stream: ws 11 128676314590080 Received webhook request 2025-03-04T00:39:38.1700588Z stderr F ERROR 2025-03-04 00:39:38,169 views 11 128676314590080 Unauthenticated user request 2025-03-04T00:39:38.1701766Z stderr F WARNING 2025-03-04 00:39:38,170 log 11 128676314590080 Unauthorized: /shopify/webhook/subscription/ Debugging Steps Taken Tested Webhook Locally: I wrote a test_webhook.sh script, which successfully sends a POST request with the correct headers and HMAC signature. The webhook persists data correctly to my Azure Postgres DB. Test Script: #!/bin/bash PAYLOAD='{"test": true, "customer": {"first_name": "Test", "last_name": "User", "email": "test@example.com"}}' SEAL_SECRET="seal_secret_****************************" SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$SEAL_SECRET" | cut -d' ' -f2) curl -X POST \ "https://vitaverde-backend.greensky-92f80007.eastus.azurecontainerapps.io/shopify/webhook/customer-creation/" \ -H "Content-Type: application/json" \ -H "X-Seal-Token: seal_token_*************************" \ -H "X-Seal-Hmac-Sha256: $SIGNATURE" \ -d "$PAYLOAD" \ -v echo -e "\n\nPayload: $PAYLOAD" echo "Signature: $SIGNATURE" Ensured CSRF Exemption for Webhook: In settings.py, I added the webhook endpoint to CSRF_EXEMPT_URLS: CSRF_EXEMPT_URLS = [ 'shopify/webhook/subscription/', 'shopify/webhook/customer-creation/', 'api/customer/webhook/seal-delivery/', ] … -
What is the proper way to handle saving a large amount of huge graphs
I currently use Django 4.2.5 and django-rest-framework 3.14.0. I need a way to handle saving a large amount of huge graphs ~1_000_000 of ~5_000 node's graph. My current database is mariadb, MySQL. I found a lot of different solutions: A graph oriented database such as Neo4j Using SQL relations, by having and intermediate database for parents / children relations Using JSON data and re-construct graph when need it in graph form But none of these solutions are fully advantaging. What solution would you recommend and why ? -
Is it a good idea to let Django server React? What are the pros and cons?
I am thinking to combine Django and React, meaning to deploy them together on a single server. May I know if it is a great idea to do so? Are there any pros and cons of that approach? Let me know your comments. Thanks in advance! I just wanted know whether if it is a great idea or not. -
Django How to deal with database locking
I have two functions, periodic_signals(), and update_choice(), and use postgres. update_choice() is called once users make a new choice, and update the database. periodic_signals() is called every 0.1s using Threading.timer, and reads users' choices from the database, and do some stuffs, then send signals back to users, and plot them in real time. When periodic_signals() is called every 1s, I don't have any problems. When periodic_signals() is called every 0.1, everything I call update_choice(), there is a pause in my plot, and I can see the execution time of update_choice() increases 10x. Is it because I read and write to the same row almost at the same time, causing database locking? How can I solve it, except to improve the performance of these two functions (at the moment both function take about 0.005-0.02s depending on the number of users)? -
Ordering data after distinct
I distinct data by sku_id queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id')) However this result is not sorted by id, then I try to queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id').order_by('id')) However this shows the error ProgrammingError at /api/myfetch/ SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("myapp_produc... Is it possible to sort the column after distinct? -
Is there a way by which I can optimize the loading time of an api right now the size of the respose is very large, so it takes a lot of time
Below is the sample response data, as you can see the target array varies and can be quite large so it takes a lot of time to load. Sure I can decouple the target array from here and expose another api with pagination just for that. But I am working on a new codebase and in the frontend the target array from the response body is being used in maybe thousands of places. So to expose a new api would be a lot of pain. Does anyone knows a good solution to optimize the laoding time of the api. { "message": "Successfully fetched notification preferences config", "data": [ { "id": 0, "label": "Star rating", "comparators": [ { "id": 0, "label": "Contains", "negation": false, "comparator": 1, "function": 0 }, { "id": 1, "label": "Does not contain", "negation": true, "comparator": 1, "function": 0 } ], "targets": [ { "target_id": 0, "target_label": "1 star", "target_value": 1 }, { "target_id": 1, "target_label": "2 stars", "target_value": 2 }, { "target_id": 2, "target_label": "3 stars", "target_value": 3 }, { "target_id": 3, "target_label": "4 stars", "target_value": 4 }, { "target_id": 4, "target_label": "5 stars", "target_value": 5 } ] }, { "id": 1, "label": "Review text", "comparators": [ … -
Getting 400 Bad request from my django app deployed on ec2
Recently i deployed my django app on aws ec2 using nginx and gunicorn. i followed this tutorial And it was successful and working fine, i was also able to make requests to this app from my deployed website,then i tried uploading a file and i got an error when i checked the logs from ec2 console this was the error 2025/03/04 06:07:17 [error] 5327#5327: *5047 client intended to send too large body: 2008288 bytes, client: 152.59.11.203, server: backendapp.caresanctum.com, request: "POST /api/upload-file/ HTTP/1.1", host: "backendapp.caresanctum.com", referrer: "https://webapp.caresanctum.com/" and ever since this i have not been able to open my base url, i get a 400 bad request error , this is so strange, i did not even open my aws console to change anything.What maybe causing this. Please let me know if more information is needed -
Generate a PDF of a dynamically bound Angular webpage and allow it to be downloaded from the Dashboard page
I have a project made with Angular and Django and MongoDB as database. I have a page at http://localhost:4200/#/print/layout This Print-Layout page is properly getting all the data from an API which brings data from Backend. If i want to Print/Save as PDF the webpage of Print-Layout page, i can do Ctrl + P for that. But now i am thinking of putting a Download PDF button at this url - http://localhost:4200/#/project Here, i will give all the necessary parameters like /?plant_id=3&project_id=121&username=pratikpol@gmail.com and other headers which are required. Even without being on that Print-layout page or viewing that Print-Layout page, can i download the webpage as PDF ??? I just want the Ctrl + P functionality to work at the Download PDF button. I want to do all this on Frontend ( Angular ) only, i cant use Backend because in Print-Layout page, I have very very complex SVGs, and some other complex Styling which are being properly handled in Angular. I have tried through Backend, and am using WeasyPrint Python library which converts HTML to PDF. Thus, i had to write same to same Django HTML template as the Angular HTML template. When the HTML file is properly made, … -
Query returns None in Celery tasks
I have a celery tasks in my application but when I try to query the database in the functions, some of them returns Does not exist or None @shared_task def email_on_assign_reviewer(submission, reviewerlist): """ Send an email to the Reviewer when they are assigned to review """ print(submission) # prints normally print(reviewerlist) # this prints the list of id of reviewers perfectly submission = Submission.objects.get(id=submission) print(submission) # this prints the submission perfectly context = {"some": "context"} for id in reviewerlist: reviewer = Reviewer.objects.filter(id=id).first() print(reviewer) #this returns none if reviewer: context['reviewer_name'] = reviewer.user.first_name utils.sendEmail( context, template="review_assign.html", to=[reviewer.user.email] ) MY VIEW def perform_create(self, serializer): submission = Submission.objects.filter(id=self.kwargs['submission_pk']).first() *SOME LOGIC* data = serializer.save() for i in reviewerlist: print(Reviewer.objects.filter(id=i).first()) # this prints the reviewers perfectly tasks.email_on_assign_reviewer.delay(submission.id, reviewerlist) MY SERIALIZER def create(self, validated_data): submission_id = self.context['submission_id'] user_ids = validated_data.pop('user_ids', []) existing_profile_ids = Somequery.objects.all() for user_id in user_ids: if user_id not in existing_profile_ids: reviewer = Reviewer.objects.create(submission_id=submission_id, user_id=user_id, ) reviewers_to_create.append(reviewer.pk) return reviewers_to_create In some tasks, the submission returns DoesnotExist -
Rest_framework error message , how do i resolve this?
from rest_framework.views import APIView from rest_framework.response import Response giving error message, i have installed djangorestframework and followed the tutor steps, but its not working -
Django CsrfViewMiddleware and exploited SubDomain
Context (Double Submit Cookie and Subdomains): When using a CSRF token with a cookie for the Double Submit Cookie method, you have to ensure the client receiving the cookie can read this cookie, and then add the CSRFToken from it into the headers of future requests to the backend. When building a frontend that's on a different (sub)domain than the backend, you have to specify the domain attribute for the cookie. For example, if the frontend is on app.example.com, while the backend is on api.example.com, then the domain for the cookie must be set to example.com, or else app.example.com will not be able to read CSRFToken from the cookie. However, this opens a vulnerability to exploited subdomains. This presentation from OWASP explains how that works. From what I understand, since we allow subdomains of example.com to read the cookie, then a malicious site like evil.example.com can be set-up to falsely set the CSRF cookie, bypassing the CSRF protection from the Double Submit Cookie method. Question Django may have a protection for this but I can hardly find any documentation on it. Specifically, it has this CSRF_TRUSTED_ORIGINS used by the CsrfViewMiddleware. This is what the docs say: CSRF_TRUSTED_ORIGINS A list of … -
How can I get the member list of log-in-ed
I am using the django and websocket. I have the script like this, a user can login a websocket group Now I want to return the list of users log-in-ed and return the list to the client. How can I make this? class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = self.scope["url_route"]["kwargs"]["room_name"] logger.info("channel_name:{} / group_name {} / room_name {}".format(self.channel_name,self.room_group_name,self.scope["url_route"]["kwargs"]["room_name"])) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.send(text_data=json.dumps({ 'channel_name': self.channel_name, 'room_group_name':self.room_group_name, 'member_list': 'how can I get the member??' })) -
Django logger only logging to console from celery worker process
I have a following logging config: "root": { "level": "ERROR", "handlers": ["console", "server_file"], }, "handlers": { "celery_file": { "class": "logging.handlers.RotatingFileHandler", "level": "DEBUG", "filename": os.path.join(ROOT_LOGS_DIR, "celery", "celery.log"), "formatter": "standard", "maxBytes": 1024 * 1024 * 50, # 50 MB "backupCount": 30, }, "server_file": { "class": "logging.handlers.RotatingFileHandler", "level": "DEBUG", "filename": os.path.join(ROOT_LOGS_DIR, "server.log"), "formatter": "standard", "maxBytes": 1024 * 1024 * 50, # 50 MB "backupCount": 30, }, "loggers": { # '': {'handlers': ["root"], "level": "DEBUG", "propagate": True, }, 'django': {'handlers': ['django'], 'level': 'DEBUG', 'propagate': False, }, "celery": { "handlers": ["celery_file"], "level": "INFO", "propagate": True, }, From celery task, log = logging.getLogger("celery.inbound_outbound_jobs") log.error("Hello, World!") # this won't be written to files. Only Console. I run this task using celery-beat and worker. celery -A log_project beat --loglevel=info celery -A log_project worker --loglevel=info But this is not writing logs to server.log and celery.log. Only console logging is happening. When running this task directly from django server and not as celery worker process, this is working in all celery.log, server.log and console. Can anyone help understand this? -
Django logging - how does propagate work?
I have a following logging config: "root": { "level": "ERROR", "handlers": ["console", "server_file"], }, "handlers": { "celery_file": { "class": "logging.handlers.RotatingFileHandler", "level": "DEBUG", "filename": os.path.join(ROOT_LOGS_DIR, "celery", "celery.log"), "formatter": "standard", "maxBytes": 1024 * 1024 * 50, # 50 MB "backupCount": 30, }, "loggers": { # '': {'handlers': ["root"], "level": "DEBUG", "propagate": True, }, 'django': {'handlers': ['django'], 'level': 'DEBUG', 'propagate': False, }, "celery": { "handlers": ["celery_file"], "level": "INFO", "propagate": True|False, }, In application, log = logging.getLogger("celery.inbound_outbound_jobs") print(log.handlers) # output: [] No handlers log.error("test") My question is : when celery logger propagate =True, will this log be handled by celery logger? Also does it propagate to root logger? when propagate=False, will log be still handled by celery logger? -
django and react access control over REST
I am new to react and webservices, I have a Django+DRF+react project. I am using one of react open source FW( not naming it because this is a theoretical question ). this FW gives you an access control API so you can implement your own. as for my little understanding, django manages access pretty well, So I managed hook up the FW access control with my DRF, which request for a permission based resource and user action and I am getting the response and its all working well(I think). just to make sure we are all on the same page, I am talking about restricting the react UI side, my DRF already managing the permissions of the data on the backend. but just so user wont even be able to see a button referencing an area out of there permission. the issue is the hit on the server, there are many calls per page and I, with my very little knowledge in this field, I'm not sure is this OK ? is this conventional ? does implementing such access control which requires API call is normal procedure ? -
Uvicorn dependency issue
I want to create a Django webserver capable of handling HTTP requests and WebSocket requests. I am using uvicorn so that both types of requests can be handled in the same server instance. Whenever I try to launch my server with the command: uvicorn core.asgi:application --host 0.0.0.0 --port 8000 I get the error message: python3.11/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 11, in import websockets.legacy.handshake ModuleNotFoundError: No module named 'websockets.legacy' Here is my conda file: name: [env-name] channels: conda-forge defaults dependencies: channels python=3.11 daphne django djangorestframework uvicorn boto3 pip pip: django-cors-headers websockets "uvicorn[standard]" I'm not sure why this is happening. I've tried pip installing all of the dependencies, reinstalling the virtual environment, but it always says "Requirement Already Satisfied". -
ModuleNotFoundError: No module named 'backend' when running my make seed data script in django-admin
I am at my wit's end as I am trying to debug and figure out what the issue is. When trying to search, I just get annoyingly AI responses which I don't want so decided to write a question here on SO. Here is my traceback: Traceback (most recent call last): File "/api/manage.py", line 22, in <module> main() File "/api/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/api/api/companies/models.py", line 5, in <module> from backend.api.models import BaseModel ModuleNotFoundError: No module named 'backend.api' make: *** [seed] Error 1 Here is my settings.py INSTALLED_APPS: INSTALLED_APPS = [ # Local apps 'api', 'api.companies', 'api.assessments', 'api.users', "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] Here is my file …