Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot resolve keyword 'mem_ev' into field in Django
I have a small Django project that consists of 2 models (Event, mem_ev) plus auth User and Profile such that Users --< mem_ev >-- Events (ie a classic many to many relationship between Users & Events). I want to be able to list all events for a member and all members for an event both of which entail a join between the main dataset and mem_ev. I have the list of events attended by a member working fine (list_member_events) but cannot get a list of members attending an event (list_event_members) working. My models.py is: from django.db import models from django.utils.text import slugify from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Delete profile when user is deleted event_count = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' #show how we want it to be displayed class Event(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50,default="", null=False) description = models.TextField() cost = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) event_date = models.DateTimeField(null=True,blank=True) attendees = models.IntegerField(default=0) class Meta: ordering = ['event_date'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Event, self).save(*args, **kwargs) class Meta: ordering = ['event_date'] def __str__(self): return self.title class mem_ev(models.Model): member_id = models.ForeignKey("Profile",on_delete=models.CASCADE) event_id = models.ForeignKey("Event",on_delete=models.CASCADE) amt_paid = models.DecimalField(max_digits = … -
Cannot determine region size; use 4-item box
I'm trying to make a QR code and I'm using pillow=11.1.0. Here's the code to generate and save the QR code: def save(self, *args, **kwargs): ## TODO:Generate QR Code # qr_code_url = f"{os.environ['HOST_URL']}/inventory/{self.part_type_id}" qrcode_img = qrcode.make(self.part_number) canvas = Image.new('RGB', (290, 290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(im=qrcode_img, box=(0,0)) buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code_data.save(f'{self.part_name}.png', File(buffer), save=False) canvas.close() super().save(*args, **kwargs) However when I do save it I'm faced with the following error: cannot determine region size; use 4-item box The line in question is: canvas.paste(im=qrcode_img, box=(0,0)) -
Hey There ! , I am new to Django and i am very interested on it and i was just curious to know How do i implement Push Notification using Fire base
, I am new to Django and i am very interested on it and i was just curious to know How do i implement Push Notification using Fire base Cloud Messaging i am having trouble to implement it on my Django Project . Well i want to implement these features: TO send Notification from student to Teacher And Vice Versa . QN. = > How do i do it ? well i need help or some best YouTube Channels to help guide me as of my recent Searches in YT {YouTube} i have not Found the best Video that matches my Querry . -
Django generates complex SQL instead of simple OR condition
I'm encountering an issue where Django's ORM is generating an unexpectedly complex SQL query from a simple function. The function checks if there are any recent or upcoming matches by applying filters for team participation and public season checks on alive matches. Instead of a straightforward OR condition, the generated SQL includes a nested subquery: SELECT COUNT(*) FROM "scheduler_season" WHERE "scheduler_season"."id" IN ( SELECT U0."id" FROM "scheduler_season" U0 WHERE (U0."enddate" >= ?::date AND U0."schedule_is_public" = ?) ) OR "scheduler_season"."id" IN (?, ?, ..., ?) Expected query: SELECT COUNT(*) FROM "scheduler_season" WHERE ("enddate" >= ? AND "schedule_is_public" = ?) OR "id" IN (?, ?, ..., ?) Why does Django create this complex subquery, and how can I modify the Django query to generate the simpler expected SQL? -
Flatpicker on django template not working on mobile device
i have interesting problem. Have this template: {# date picker #} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"/> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/bg.js"></script> <link rel="stylesheet" type="text/css" href="{% static "custom/date_picker.css" %}"/> <script> document.addEventListener("DOMContentLoaded", function () { // Ensure Flatpickr's localization is loaded before modifying if (flatpickr.l10ns && flatpickr.l10ns.bg) { flatpickr.l10ns.bg.rangeSeparator = " до "; } else { console.warn("Bulgarian locale not found, continuing without modifying rangeSeparator."); } const dateTimePickers = ["#fromInput", "#toInput"]; dateTimePickers.forEach(selector => { flatpickr(selector, { enableTime: true, time_24hr: true, locale: "bg", dateFormat: "H:i ч. на d M Y г.", enableSeconds: false, // Ensure seconds are not required disableMobile: true // Forces Flatpickr UI on mobile }); }); </script> then i have this two inputs <div style="margin-top: 15px" id="fromDiv"> <label for="fromTime">От</label> <input type="text" id="fromInput" name="fromTime" placeholder="Избери дата и час" style="margin: auto"> </div> <div style="margin-top: 15px" id="toDiv"> <label for="dateTimeInput">До</label> <input type="text" id="toInput" name="toTime" placeholder="Избери дата и час" style="margin: auto"> </div> everything works perfectly on desktop browser, but when is used on mobile device, inputs change, want seconds, but in choice pop up its not possible to be selected seconds. Examples on desktop browser: how looks input and choice pop-up on desktop browser Examples on mobile: pop-up choice on mobile browser and date-time input on mobile browser.. how … -
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??' }))