Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket not receiving messages from Django Channels
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages my asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing.py: from django.urls import re_path from .consumers import DepartmentCreatedConsumer websocket_urlpatterns … -
Django Admin Recent Actions in a react Js website
I want to know if I can use the logs that are displayed on Django Admin in a custom React Js Admin Panel. I have a requirement which is to show all recent changes done by any user. Django admin already has that Recent Actions widget. How can I use that data and serialize it in some API/View I tried using django-simple-history but it shows specific history for a specific object. I want a complete generic log list -
Django: Implementing fund reversal in post_save signal
I'm using django post_save signal to update the status of a transaction based on whether funds are received. The problem is that funds_received is not working as expected. The issue is in using .exists(), because, it checks if there is any account with the exact balance equal to the transaction amount. If anyone has suggestions or knows of a better way for checking if funds are received, I would greatly appreciate the guidance. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Transaction, Account @receiver(post_save, sender=Transaction) def transaction_status(sender, instance, created, **kwargs): if created: amount = instance.amount sender_account = instance.sender.account receiver_account_number = instance.account_number receiver_account = account.objects.get(account_number=receiver_account_number) check_if_funds_received = Account.objects.filter(account_balance=amount).exists() funds_received = check_if_funds_received if funds_received: instance.status = 'Reversed' instance.save() else: instance.status = 'Reversed' instance.save() # return funds to sender sender_account.account_balance += amount sender_account.save() My Models: class Account(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.BigIntegerField(unique=True) account_balance = models.DecimalField(max_digits=12, decimal_places=6) account_id = models.CharField(max_length=15, unique=True) user_qrcode = models.ImageField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) account_status = models.CharField(max_length=50, choices=ACCOUNT_STATUS) pin = models.CharField(max_length=4) def __str__(self): return str(self.user.first_name) class Transaction(models.Model): STATUS = ( ('Success', 'Success'), ('Reversed', 'Reversed') ) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='receiver') amount = models.DecimalField(max_digits=12, decimal_places=6) account_number = models.BigIntegerField() first_name … -
stocks quantity only decreasing not increasing
after updating the data, the stocks. Quantity is only decreasing does not matter if we only increase the quantity or decrease the quantity. I want when we update the data the stocks quantity will also be updated for ex-, we increase 2 points then only 2 quantities will be decreased. suppose we have 5 unit of shoes in cart and stocks have 10 quantities left so if we increase 2 so the total quantity will in cart 7 and left quantity in stocks will be 8 quantity shoes and if we decrease 3 quantities so the total quantity in cart will be 4 and total quantity in stocks are 11. for ex-, we increase 2 points then only 2 quantities will be decreased. suppose we have 5 unit of shoes in cart and stocks have 10 quantities left so if we increase 2 so the total quantity will in cart 7 and left quantity in stocks will be 8 quantity shoes and if we decrease 3 quantities so the total quantity in cart will be 4 and total quantity in stocks are 11. I just need the logic. hope you guys get that! ================================================================================== views.py > def supplier_edit(request, id): try: … -
problem loading static files with django nginx gunicorn on AWS lightsail
I installed my django app on lightsail, on a ubuntu server from scratch. The webpage is working ok but the static files are not loading. I read about adding some info on the web_app.conf (cht_web.conf) and it looks like this: `server { listen 80; server_name xxx.xxx.xxx.xxx; location / { include proxy_params; ` proxy_pass http://localhost:8000/; } location /static/ { autoindex on; root /home/ubuntu/cht_web/cht_web/static/; } I´m not sure if i have to install Supervisor, so I´ve not installed it yet, im running gunicorn with: gunicorn cht_web.wsgi --bind 0.0.0.0:8000 --workers 4 and the log is: \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Starting gunicorn 21.2.0 \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Listening at: http://0.0.0.0:8000 (38774) \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Using worker: sync \[2023-11-20 12:47:13 +0000\] \[38775\] \[INFO\] Booting worker with pid: 38775 \[2023-11-20 12:47:13 +0000\] \[38776\] \[INFO\] Booting worker with pid: 38776 \[2023-11-20 12:47:13 +0000\] \[38777\] \[INFO\] Booting worker with pid: 38777 \[2023-11-20 12:47:13 +0000\] \[38778\] \[INFO\] Booting worker with pid: 38778 my settings.py static config is: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' #representa la raiz del directorio STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), my base dir is: BASE_DIR = Path(__file__).resolve().parent.parent (maybe the extra.parent is an issue, but it loads media!) Its in debug … -
Django app, how to download all files asociated a project?
I'm trying to create a definition in my view.py file to download all files associated with a project. This time I'm using the python ZipFile package to zip all the files, but I'm having a lot of trouble finding the right code My Models class File(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) project_slug = AutoSlugField(populate_from='project', always_update=True) pub_date = models.DateTimeField(auto_now_add=True) def directory_path(instance, filename): return 'files_project/project_{0}/{1}'.format(instance.project_slug, filename) upload = models.FileField(upload_to=directory_path) My view def DownloadAllFilebyProject(request, id): project = Project.objects.get(id=id) files = project.file_set.all() zf = zipfile.ZipFile(os.path.join(settings.MEDIA_ROOT, 'files_project/project_{0}/'.format(project.slug), 'allfile.zip'), 'w') for file in files: zf.writestr(os.path.join(settings.MEDIA_ROOT, 'files_project/project_{0}/'.format(project.slug)), file) zf.close() return HttpResponse(print(zf)) My Template <a href="{% url 'apppro:DownloadAllFilebyProject' project.id %}" class="btn btn-warning float-right" method="get"> descargar todos los archivos</a> The error TypeError at /downloadallzipfiles/13 object of type 'File' has no len( -
POST data not registering in Django custom admin action with intermediate form
I am trying to add a custom admin action do my Django model. The goal is to show a form to the user where they can select a group which will get linked to all my selected candidates. My issue is that the code works in the render part, and the form is shown. However when I click apply my code never enters the if 'apply' in request.POST condition. It also seems the code is never called a second time. Here are the relevant parts of my code: CandidateAdmin.py from django.contrib import admin from django.utils.safestring import mark_safe from exem_poi.models import Candidate from django.urls import reverse from django.utils.html import format_html from django.http import HttpResponseRedirect from django.shortcuts import render from exem_poi.views.utils import convert_to_wgs84 from exem_poi.models.Candidate import Group @admin.register(Candidate) class CandidateAdmin(admin.ModelAdmin): list_display = ('batiment_construction_id', 'emitters_100m', 'height', 'display_owners', 'is_public') list_filter = ('emitters_100m', 'height', 'is_public') search_fields = ('batiment_construction_id', 'emitters_100m', 'height', 'is_public') readonly_fields = ('centroid',) actions = ['assign_to_group'] def assign_to_group(self, request, queryset): # Handle the form submission for assigning candidates to a group print(request.POST) if 'apply' in request.POST: group_id = request.POST.get('group_id') group = Group.objects.get(id=group_id) for candidate in queryset: group.candidates.add(candidate) self.message_user(request, f'Successfully assigned candidates to group {group.name}') return HttpResponseRedirect(request.path) groups = Group.objects.all() context = {'groups': groups, 'candidates': … -
How to join multiple models with OnetOne relationship in Django?
I have a main model with several fields and a few other models that serve as extra information which varies depending on user input. The main model will always be related to one of these. I want to retrieve all the information between the main models and the models with extra information. Here's an example of the relationship: class MainModel(models.Model): MAIN_MODEL_CHOICES = [(1, "Extra info 1"), (2, "Extra info 2"), (3, "Extra info 3")] name = models.CharField(max_length=100) description = models.CharField(max_length=100) choice = models.IntegerField(choices=MAIN_MODEL_CHOICES) class ExtraModel1(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) extra_text_info = models.TextField() class ExtraModel2(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) important_number = models.IntegerField() class ExtraModel3(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) important_bool = models.BooleanField(default=False) I have tried MainModel.objects.prefetch_related("extramodel1", "extramodel2", "extramodel3") and MainModel.objects.select_related("extramodel1__main_model", "extramodel2__main_model", "extramodel__main_model") but the retrieved queryset doesn't include the extra models, only the main one. -
Celery Tasks not Running on Mac M2 (Process 'ForkPoolWorker' exited with 'signal 11 (SIGSEGV)')
I am encountering an issue while trying to run Celery tasks on my Mac M1 machine. The error message I'm getting is as follows: The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec(). Break on __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__() to debug. [2023-11-20 15:51:19,174: ERROR/MainProcess] Process 'ForkPoolWorker-8' pid:5547 exited with 'signal 11 (SIGSEGV)' I am using Celery for my Django app task processing, and this issue seems to be related to forking on the M2 architecture. I initially attempted to resolve the issue by exporting OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES, which seemed to work for a brief period. However, the problem has resurfaced, and this solution no longer has any effect. It's worth noting that I am currently running MacOS Sonama 14.2 Beta on my machine. Interestingly, I encountered and successfully resolved this problem once before while on the same beta program. Any insights or suggestions on how to resolve this issue would be greatly appreciated. -
How to connect react native with android studio with django docker container?
I have a react native app for web configured. And I have a django app for the backend. I can connect this two apps with each other. But now I have dockerized the django app. But not the react app. And now the react app cannot any more communicate with the django docker app. So this is my docker compose.yml file: version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dierenwelzijn\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: name DB_PASS: pass DB_USER: user DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: tcp volumes: - type: bind source: C:\repos\dierenwelzijn\dwl_backend\DierenWelzijn target: /app bind: create_host_path: true db: environment: POSTGRES_DB: db POSTGRES_PASSWORD: password POSTGRES_USER: user image: postgres:13-alpine networks: default: null volumes: - type: volume source: dev-db-data target: /var/lib/postgresql/data volume: {} networks: default: name: dwl_backend_default volumes: dev-db-data: name: dwl_backend_dev-db-data and my login method for react looks like: export const loginRequest = async (email, password) => { try { const response = await fetch("http://192.168.1.135:8000/api/user/token/", { … -
Notifications not showing on list
I have a django app with django-notifications-hq installed. The notifications are working pretty well except for the list of notifications aren't showing on the field. The notifications count is showing in the navbar. Here's my code : <div class="dropdown"> <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bell" viewBox="0 0 16 16"> <path d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 2.197-.459 3.742-.16.767-.376 1.566-.663 2.258h10.244c-.287-.692-.502-1.49-.663-2.258C12.134 8.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z"/> </svg> {{ request.user.notifications.unread.count }} </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> {% for notification in notifications %} <a class="dropdown-item" href="{{ notification.data.action_object.get_absolute_url }}"> Notification: {{ notification.actor }} {{ notification.verb }} </a> {% empty %} <span class="dropdown-item">No notifications</span> {% endfor %} </div> </div> I've tried to consult ChatGPT but don't get any answers. So any help from this community would be a great one. Also, if you need me to post anything else, I would definitely post it here. -
Django does not load the maps in the admin panel
I need to upgrade the Django version of a project that uses GeoModelAdmin for displaying maps in the admin panel. The recommended class to be used is ModelAdmin as stated in the documentation: Deprecated since version 4.0: This class is deprecated. Use ModelAdmin instead. However, when I use ModelAdmin the maps do not load at all. And I get this error in the console: GET https://gitc.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_ShadedRelief_Bathymetry/default/%7BTime%7D/GoogleMapsCompatible_Level8/8/92/146.jpg 500 (Internal Server Error) Is there a configuration that I missed or there are problems with the server? In the past I used OSMGeoAdmin which was exactly what I needed, but got it deprecated in Django 4.0. Now is suggested to use GISModelAdmin instead. When I use GISModelAdmin the maps are loaded, but I want to configure the zoom level and if I set the gis_widget_kwargs according to the documentation, nothing changes. gis_widget_kwargs = { "attrs": { "default_lon": 5, "default_lat": 47, "default_zoom": 3, } } -
Django .initial attribute in the form seems doesn't work
I have a problem with my Django project. I have a Model "Fattura" and a Form "EntrataForm", here is the code of the model: class Fattura(models.Model): TIPO_CHOICES = [ ('T', 'Tasse'), ('B', 'Burocrazia'), ('C', 'Clienti'), ('S', 'Spese'), ] numero = models.CharField(max_length=20) data = models.DateField(default=django.utils.timezone.now) tipo = models.CharField(max_length=1, choices=TIPO_CHOICES) importo = models.DecimalField(max_digits=10, decimal_places=2) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True, blank=True) viaggi = models.ManyToManyField(Viaggio) def clean(self): if self.importo is None: raise ValidationError('L\'importo non può essere None.') def __str__(self): return f"{self.numero} - {self.data} - {self.importo} - {self.tipo}" and the form: class EntrataForm(forms.ModelForm): class Meta: model = Fattura fields = ['numero', 'data', 'cliente','viaggi','importo','tipo'] def __init__(self, *args, **kwargs): id = kwargs.pop('id',None) super(EntrataForm, self).__init__(*args, **kwargs) importo_finale = 0 viaggi = Viaggio.objects.filter(cliente_id=id) for viaggio in viaggi: importo_finale += viaggio.prezzo_viaggio print(id) self.fields['tipo'].widget.attrs['readonly'] = True self.fields['tipo'].required = False self.fields['tipo'].widget = forms.HiddenInput() self.fields['tipo'].initial = 'C' self.fields['viaggi'].widget.attrs['readonly'] = True self.fields['viaggi'].required = False self.fields['viaggi'].widget = forms.HiddenInput() self.fields['viaggi'].initial = viaggi self.fields['cliente'].widget.attrs['readonly'] = True self.fields['cliente'].required = False self.fields['cliente'].widget = forms.HiddenInput() self.fields['cliente'].initial = Cliente.objects.get(id=id) self.fields['importo'].widget.attrs['readonly'] = True self.fields['importo'].required = False self.fields['importo'].widget = forms.HiddenInput() self.fields['importo'].initial = importo_finale print(self.fields['importo'].initial) As you can see i use the ".initial" attribute for 4 fields, but only "importo" doesn't initialize correctly. In init the final value is correct and the last line … -
Allow Admin user to see only the user the admin creates in Django
I am trying to create a school management system, where by a school can register and becomes an admin, the school which is an admin, can create their staffs and students. The staff and students should be able to login to their accounts. The key thing here is that, there will be more than one school registered, thus each school should only see their own staffs and students. How can i ensure that the admin only sees the students and staff account created by that admin alone? Functionality so far I have created different user type accounts, admin(school) can login and create a student and staff accounts, students and staffs account created by admin which is the school can also login. The thing here is that, all admin can see all staffs, i don't want this to happen, i want admin to only see the student and staffs created by that admin alone. Below is my code for review accounts/models.py my custom user model class CustomUser(AbstractUser): USER_TYPE = ((1, "school"), (2, "Staff"), (3, "Student")) GENDER = [("M", "Male"), ("F", "Female")] username = None # Removed username, using email instead email = models.EmailField(unique=True) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) gender = models.CharField(max_length=1, … -
DJango and Docker: db shutting down and web service not accepting connections
I have a problem with Docker. I am trying to build a docker postgres DB and web service for a DJango app. Here is my config: Dockerfile: # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml: services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=whatsarounddb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin123 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=whatsarounddb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin123 depends_on: - db settings.py from Django: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] **code** # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'whatsarounddb', 'USER': 'dbadmin', 'PASSWORD': 'dbadmin321', 'HOST': 'localhost', 'PORT': 5432, } } When I use docker-compose up --build I get the following output: [+] Running 14/1 ✔ db 13 layers [⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿] 0B/0B Pulled 9.6s [+] Building 7.0s (14/14) FINISHED docker:default => [web internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [web internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 234B 0.0s => [web] resolve image config for docker.io/docker/dockerfile:1 1.5s => [web auth] docker/dockerfile:pull token for … -
Django Add Multiple Files To Single Instance
enter image description here MY Problem is when i click on extension ID it should display all the audio files relegated to that ID is there any way to upload multiples files Audio Files For Single Instance enter image description here Here Is The Second Image It Showing Only One Audio File But I want to upload multiple audio files trying to create different form applying different method in model -
Failed to get Xrpl NFt history using JSON RPC request's "nft_history" method
Hello community memebers, I'm unable to get the NFT history. I tried to get the NFT history throgh the below given snippet. from django.http import JsonResponse def get_nfthistory(request): JSON_RPC_URL = "https://s.altnet.rippletest.net:51234/" if request.method != 'POST': return JsonResponse({'success': False, 'error': 'Invalid request method'}) nft_id = request.POST.get('nft_id') # Initialize JSON-RPC client client = JsonRpcClient(JSON_RPC_URL) print(client) try: response_data = client.request(NFTHistory(nft_id=nft_id)) print(response_data) return JsonResponse({'success': True, 'data': response_data}) except Exception as e: return JsonResponse({'success': False, 'error': str(e)}) I've written this django view function in order to get NFT history. I took XRPL NFT History method as reference. And, the **NFTHistory ** in the "response_data = client.request(NFTHistory(nft_id=nft_id))" is a standard class defined in the xrpl model package. Here is the class code: """ The `nft_history` method retreives a list of transactions that involved the specified NFToken. """ from dataclasses import dataclass, field from typing import Any, Optional from xrpl.models.requests.request import LookupByLedgerRequest, Request, RequestMethod from xrpl.models.required import REQUIRED from xrpl.models.utils import require_kwargs_on_init @require_kwargs_on_init @dataclass(frozen=True) class NFTHistory(Request, LookupByLedgerRequest): """ The `nft_history` method retreives a list of transactions that involved the specified NFToken. """ method: RequestMethod = field(default=RequestMethod.NFT_HISTORY, init=False) nft_id: str = REQUIRED # type: ignore """ The unique identifier of an NFToken. The request returns past transactions of … -
I am trying to pass some json data from my django web app to a server running at localhost. Works fine at localhost but fails in production
I have a server running at 127.0.0.1:16732. I am passing json data to this server from my django app: response=requests.post('http://127.0.0.1:16732/api/v2/requests', auth=auth, json=task) Works fine when I do it from my test python server on localhost. But when I try to do the same from production server, it fails & give the following error: "HTTPConnectionPool(host='localhost', port=16732): Max retries exceeded with url: /api/v2/requests (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f3e335006d0>: Failed to establish a new connection: [Errno 111] Connection refused'))" -
ValueError: Cannot assign "'827'": "Course_Content.course_outline_id" must be a "Course_Outline" instance
So in my django view i am trying to pass the outline instance but it keeps saying ValueError: Cannot assign "'827'": "Course_Content.course_outline_id" must be a "Course_Outline" instance. I already tried converting it to int. But i dont know what i am doing wrong. I already tried using outline_instance.id so it would be more specific it still does not work. views.py class UpdateCourseOutline(View): def post(self, request): outline_id = request.POST.get('outline_id', None) new_topic = request.POST.get('new_topic', None) new_week = request.POST.get('new_week', None) new_clo = request.POST.get('new_clo', None) new_course_content_data = json.loads(request.POST.get('new-course_content', '[]')) deleted_course_content_data = json.loads(request.POST.get('deleted-course_content', '[]')) new_added_course_content_data = request.POST.getlist('add-new-course_content[]') # Update Course_Outline details outline = get_object_or_404(Course_Outline, id=outline_id) outline.topic = new_topic outline.week = new_week outline.course_learning_outcomes = new_clo outline.save() print("outline - type(outline_id):", type(outline_id)) # Add new Course_Content items self.add_course_content(int(outline_id), new_added_course_content_data) # Update Course_Content details self.update_course_content(outline_id, new_course_content_data) # Delete Course_Content items self.delete_course_content(deleted_course_content_data) # Retrieve the updated outline with course content updated_outline = Course_Outline.objects.values('id', 'topic', 'week', 'course_learning_outcomes').get(id=outline_id) updated_outline['course_content'] = list(Course_Content.objects.filter(course_outline_id=outline_id).values('id', 'course_content')) data = { 'success': True, 'message': 'Course outline updated successfully!', 'outline_id': updated_outline['id'], 'topic': updated_outline['topic'], 'week': updated_outline['week'], 'course_learning_outcomes': updated_outline['course_learning_outcomes'], 'course_content': updated_outline['course_content'], # Add other fields if needed } return JsonResponse(data) def add_course_content(self, outline_id, new_values): try: # Get the Course_Outline instance based on the outline_id outline_instance = get_object_or_404(Course_Outline, id=outline_id) # Log information … -
How to run an application automatically and in the background in Django?
I have an application that displays on a page a stream from a video camera on which detections are indicated. I need to count them for further statistics. The problem is that all the script logic only works if I open a specific page. That is, I opened the “Camera1” page, saw the video stream from it and the script detects and counts the objects in the frame. If I open "Camera2" - the same. I need these scripts to work even when the page is not open. That is, for example, after rebooting the server, the Django application is automatically launched and, as it were, the opening of all pages from the cameras is simulated so that the scripts start working. In a word, I need the script to work even if it is not called directly on the page. Is this possible and if so - how? Thank you -
Kerberos Implementation in Django
How do i implement an Kerberos SSO in Django? I am new to Django and need something like a Documentation or Tutorial on how to integrate KErberos and LDAP as SSO in a Django app. I've searched now for a long time and did not find any complete or reasonable solution. -
Django AWS Elastic Beanstalk - 502 Bad Gateway
I have been trawling the internet looking for a solution to this problem and have come up empty handed after trying multiple different things. Im looking to get the vanilla django project deployed on AWS EB. I am new to this so I am sure there is something simple that I am missing. I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html as well as many other YouTube / Stack tutorials and posts hoping to get around this 502 error. Here is my setup. project setup This is my django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application Here is my config.yml file: branch-defaults: default: environment: django-env2 group_suffix: null global: application_name: django-tut branch: null default_ec2_keyname: null default_platform: Python 3.9 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application In Settings.py the only change I made was: ALLOWED_HOSTS = ['django-env2.eba-wftrfqr2.us-west-2.elasticbeanstalk.com'] This is requirements.txt asgiref==3.7.2 Django==3.1.3 pytz==2023.3.post1 sqlparse==0.4.4 typing_extensions==4.8.0 When I run the server locally it works perfectly, giving the generic django page on http://127.0.0.1:8000/ (this is before I update ALLOWED_HOSTS of course). In console its status turns to "Severe" and a warning event is displayed: "Environment health has transitioned from Pending to Severe. ELB processes are not healthy on … -
Content security policy(CSP) in django Project
We need to implement content security policy(CSP) in our Django project, I am not able to apply CSP in inline style and inline script, Please suggest any solution? We are using nonce and hashes for validation inline script and inline style, Nonce is working in tag, but not working in tag & inline style. please suggest any solution. -
"django-admin is not recognized as internal or external command"
I have installed django, but still it shows "django-admin is not recognized as internal or external command". installed the updated version but shows me the same error. I am trying to build a project using django. I have tried to install django everytime I opened prompt and couldn't move past this problem. I need a solution to solve this problem -
How do I create an Instagram login and registration page in Django? [closed]
How do I create an Instagram login and registration page in Django? I searched a little on the internet, the information tired me, so I didn't get a good result. Can you help me with some code and explanation? I want to add a feature to log in and record Instagram in Django.