Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django File Upload Not Working: Media File Missing and Full Path Issue
I'm working on a Django project where I'm trying to handle file uploads, but I'm encountering some issues. The uploaded files are missing, and I don't have the full path to the media files. Here's what I've done so far: Models I have a model with a FileField for uploads: class Article(TrackingModel): titleArt = models.CharField(max_length=200) descriptionArt = models.TextField() content = models.FileField(upload_to='articles/%Y/%m/%d') section = models.ForeignKey(Section, on_delete=models.CASCADE) is_accepted = models.BooleanField(default=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titleArt Settings I'm using the following settings for media files: MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = 'media/' URLs I've set up the URL patterns like this: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('ciems_administration/', include('administration.urls')), path('auth/', include('accounts.urls')), path('', include('intelsight.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Template Here's a snippet of the template where I show the file details: <div class="container"> <h1>Report Details</h1> {{ article.titleArt }}<br> {{ article.descriptionArt }}<br> {{ article.content.url }}<br> {{ article.section }}<br> {{ article.created_at }}<br> {{ article.updated_at }}<br> <a href="{% url 'articleList' %}" class="btn btn-primary">Back</a> </div>[](https://i.sstatic.net/O9jkZnK1.jpg) Problem The uploaded file paths are shown as /media/..., but the files are not actually present in the media directory. The file upload doesn't seem to … -
Running `collecstatic` returns [Errno 13] Permission denied in docker compose
I run my django app in Docker. I recently tried running collecstatic and instead was given this error code: >docker-compose exec web python manage.py collectstatic Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() ... PermissionError: [Errno 13] Permission denied: '/code/static/admin/img/tooltag-arrowright.bbfb788a849e.svg.gz' I added a USER at the end of my Dockerfile so that the USER isn't root which I know is a security vulnerability. Here is my Dockerfile: # Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ && apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \ && rm -rf /var/lib/apt/lists/* # Set working directory for Docker image WORKDIR /code/ # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Create a custom non-root user RUN useradd -m example-user # Grant necessary permissions to write directories and to user 'example-user' RUN mkdir -p /code/media /code/static && \ chown -R … -
Is it possible to have a child model with multiple parents in a Django App?
I am creating a quiz back-end. I would like to add a feature where a user can report a question for being irrelevant or not fair. I have 3 relevant models for this in my Django app: User Model Question Model Report Model I would like to record what user created the report and also what question was reported. Is it possible to have a Many to 1 relationship between Report:User and also a Many to 1 relationship between Report:Question too? The report model would have two parents - User and Question. Is there a better way of doing this? -
creating reports in arabic with django
iam trying to create a report using django but the arabic word coes out redacted for some reason this is the and example of the pdf this is my view function this function and templates works just fine with downloading the pdf but when it comes out to rendering arabic it does't work i have downloaded this arabic font NotoKufiArabic-VariableFont_wght.ttf but it won't work for some reason from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO from django.shortcuts import get_object_or_404 from ..models import Supplier, TransactionModel from django.db.models import Sum def generate_pdf_report(request, supplier_name): supplier = get_object_or_404(Supplier, supplier_name=supplier_name) transactions = TransactionModel.objects.filter(supplier_name=supplier).order_by('payment_date') total_paid = transactions.aggregate(Sum('payment_amount'))['payment_amount__sum'] or 0 remaining_amount = supplier.total_amount - total_paid context = { 'supplier': supplier, 'transactions': transactions, 'total_paid': total_paid, 'remaining_amount': remaining_amount, } template = get_template('supplier_report.html') html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{supplier_name}_report.pdf"' return response return HttpResponse('Error generating PDF', status=400) and this is my template <html lang="ar" dir="rtl"> <head> <meta charset="UTF-8"> <title>تقرير المورد - {{ supplier.supplier_name }}</title> <style> @font-face { font-family: 'Arabic Font'; src: url('../../NotoKufiArabic-VariableFont_wght.ttf') format('truetype'); } body { font-family: 'ArialArabic', Arial, sans-serif; direction: rtl; text-align: right; } table { … -
Loading Css in django template
Using Django template, i made some HTML files and one base.html, while I'm in local, there are zero issues, everything loads perfectly, while I'm production however, the base.html css won't load, everything else loads, images , js, and even the css of other stuff ( i ran collectstatic ) but this particular one doe not load, i load it up using tags <link rel="stylesheet" href={% static "css/style.css" %} exactly like this in other templates, all the css files are inside a folder called ***/public_html/static/css and in my settings.py, i have this line STATIC_ROOT = '/somepath/public_html/static' after running collectstatic, Django put all of my img, css,js and vids and put them inside this folder so : /somepath/public_html/static/ |img/ |vid/ |css/ |js/ what am i doing wrong? why every things load properly including all the img and css but the css of Django templatebase.html doesn't ? base.html is the template file that most template extend from it using Django template extend feature. So far i haven't tried anything special, if i load the css manually, it works, it just that when i extend the html using Django template it doesn't, I'm using Django version 3.x.x however and not the latest one on … -
Azure AppService with Django on Linux using Azure Devops for CI takes 20 minutes
I am using Django on Linux with Azure Devops as Continuous Integration / Continuous Development purposes. I have succesfully setup the yaml file for deployment and associated with Azure AppService which seems to be working ok. However it takes a long time ( about 20 minutes ), it was a lot faster with other cloud providers ( such as 3-4 minutes ) Here below is my azure-pipelines-prod.yaml file : # Python to Linux Web App on Azure # Build your Python project and deploy it to Azure as a Linux Web App. # Change python version to one thats appropriate for your application. # https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - main variables: # Azure Resource Manager connection created during pipeline creation azureServiceConnectionId: 'xxxxxxxx-7f93-4dc6-922b-ae9b29311fbf' # Web app name webAppName: 'project-app' # Agent VM image name vmImageName: 'ubuntu-latest' # Environment name environmentName: 'project-app' # Project root folder. Point to the folder containing manage.py file. projectRoot: $(System.DefaultWorkingDirectory) pythonVersion: '3.9' stages: - stage: Build displayName: Build stage jobs: - job: BuildJob pool: vmImage: $(vmImageName) steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(pythonVersion)' displayName: 'Use Python $(pythonVersion)' - script: | python -m venv antenv source antenv/bin/activate python -m pip install --upgrade pip pip install setup pip install --target="./antenv/lib/python3.9/site-packages" -r … -
Front-end development failed to introduce css
When using Django, the front end successfully introduces css, but does not display on the pageenter image description here The python version is OK, the development framework is OK, the css writing is OK, the css is confirmed to have been successfully introduced, and the css path is OK。 -
Django not connecting to proper DB [closed]
I'm building a rather small backend component with Django and I got it connected to an external Postgre DB. The issue is, when I started the Django app and tried to fetch some data all I got is a 204 No content response (which is what I'd expect if there is no data in DB) but the DB has data, which make me think my app is not connecting to the proper DB. This is my DB config which was working before and is working in my deployed component: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USERNAME'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': os.environ.get('DATABASE_PORT'), } } There is no error showing up at all, just my DB has some test data which I can access through pgAdmin (pgAdmin result) and I also can get the data through postman calling the current deployed component (GET /api/products/ HTTP/1.1" 200 899 "-" "PostmanRuntime/7.41.0"/) -
Django as_field_group?
How can I modify the as_field_group method to change the order of its returned values? Currently, the method returns the label, error message, and then the input field. However, I want to customize it so that it returns the label first, then the input field, and finally the error message at the end. How can I either override or customize the as_field_group method to achieve this? -
How to retrieve filtered queryset used to render form fields in Django?
I have a Django form that contains a table with rows that reflect course objects from a database . Each row contains a checkbox input. This form also has some submit buttons that allow the user to filter the course objects shown in the table (besides a generic submit button). This form is used to update the users profile with courses they are interested in. When the form is submitted, courses in the filter that are unchecked should be removed from the interested M2M relation and checked ones should be added to it. To do that I need to know which inputs are checked , which I know how to retrieve, but I also need to know which courses are in the table that have unchecked inputs. Retreiving this is not as easy as ‘all the other courses in the database’ because my table does not always contain all course objects. If a user previously clicked one of the filter buttons, then the table contains only a filtered set of courses. So I need to know which courses were used to create the table at rendertime, i.e. the ones that were injected as HTML context variable. Of course I know … -
Django app with Amazon RDS works fine in localhost, but after deployed on Elastic Beanstalk unable to get data from RDS
This is a tutorial project available on w3schools. My app can access and update PostgreSQL database stored in amazon RDS while running in local virtual environment. I deployed the project on Elastic Beanstalk. It opens and shows the pages as it should, but when database involves keep-on loading and throughs "504 Gateway Time-out". Database : PostgreSQL app link : http://mydjangoapp-env.eba-mppp6a3b.ap-south-1.elasticbeanstalk.com/ source-code : https://github.com/jyotiskaborah/my_tennis_club.git I tried to check my settings.py file no error found. Please help me to fix this issue. I guess there is some permission related settings which causing this error. -
how to configure nginx so that front end and backend works in AWS
i am deploying my app on AWS instance. i have both frontend and backend as docker image. i want to use nginx. when i run this config, and go to AWS given public URL, then 502 is returned by nginx. /api /docs they are working but /admin / returning 502. here is my conf files: docker-compose.yml: backend: container_name: backend image: ${BACKEND_IMAGE_NAME}:${IMAGE_TAG} command: python manage.py runserver 0.0.0.0:8000 env_file: - .env expose: - 8000 frontend: container_name: frontend image: ${FRONTEND_IMAGE_NAME}:${IMAGE_TAG} expose: - 3002 env_file: - .env nginx: build: ./nginx ports: - 80:80 depends_on: - backend - frontend here is nginx conf: upstream backend { server backend:8000; } upstream frontend { server frontend:3002; } server { listen 80; location /api/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /docs/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /admin/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location / { proxy_pass http://frontend; # Proxy to frontend on port 3002 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; # Ensure that Nginx handles large files and requests well client_max_body_size 100M; # Timeout settings to prevent 502 Bad Gateway proxy_connect_timeout 600; proxy_send_timeout 600; … -
How to customize Django Oscar category_tree template tag and remove pk from category URLs?
I'm working on an eCommerce project using Django Oscar, and I've run into an issue that I can't seem to solve. My goal is to customize the category URLs to only use slugs instead of both slug and pk, but I'm having trouble implementing this. Here's what I've done so far: What I Want to Achieve: I want to remove the pk from the category URLs in Django Oscar. Right now, my URLs look like this: http://127.0.0.1:8000/category/metal-detectors_2/ I would like them to look like this: http://127.0.0.1:8000/metal-detectors/ My Setup: I'm using a forked catalogue app from Django Oscar, where I'm making my customizations. I have a custom template categories.html in which I am trying to loop through categories and their child categories. I have created a custom template tag category_tree in a templatetags folder under the catalogue app to handle category rendering. Problem: I am using the {% category_tree as tree_categories %} template tag to render categories, but it seems to be failing due to the use of pk in the URL construction. I want to modify it to only rely on the category_slug. However, I keep getting the following error: NoReverseMatch: Reverse for 'category' with keyword arguments '{'category_slug': 'metal-detectors', 'pk': … -
FOREIGN KEY constraint failed in Django Python
I am trying to make a cabbie accept accept a ride but couldn't. FOREIGN KEY constraint fail Ride is available to accept when it is created and is in temporary phase While accepting the cabbie and his vehicle will be assigned to ride But Foreign Key constraint fails Model: class Ride(models.Model): STATUS_CHOICES = [ ('Temporary', 'Temporary'), ('Passenger Confirmed', 'Passenger Confirmed'), ('Cabbie Confirmed', 'Cabbie Confirmed'), ('Cancelled', 'Cancelled'), ('Completed', 'Completed'), ] pick_up = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='pick_up') drop = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='drop') distance = models.DecimalField(decimal_places=2, max_digits=7) fare = models.DecimalField(decimal_places=2, max_digits=7) passenger = models.ForeignKey(User, on_delete=models.PROTECT, related_name='rides') cabbie = models.ForeignKey(User, on_delete=models.PROTECT, related_name='driven_rides', null=True, blank=True) vehicle_type = models.ForeignKey(VehicleType, on_delete=models.PROTECT, related_name='rides', null=True, blank=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name='rides', null=True, blank=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Temporary') accepted_at = models.DateTimeField(null=True, blank=True) completed_at = models.DateTimeField(null=True, blank=True) def calculate_fare(self): return (self.distance * self.vehicle_type.farekm) + self.vehicle_type.charges def __str__(self): return f"Ride from {self.pick_up} to {self.drop} - Status: {self.status}" View: def accept_ride(request, ride_id): # Fetch the ride object or return 404 if not found ride = get_object_or_404(Ride, id=ride_id) # Check if the user is a Cabbie if not request.user.groups.filter(name='Cabbie').exists(): messages.error(request, "You must be a cabbie to accept this ride.") logger.info(f"User {request.user.username} attempted to accept a ride but is not a cabbie.") return redirect('CabbieDashboard') if … -
How to configure two server domains in django-anymail
I'm working on a Django project and using Anymail with Mailgun to send emails. I have two domains pointing to same site domain1.com and domain2.com I set up mailgun both senver domains as mg.domain1.com and mg.domain2.com both with their api key. Both domains worked fine when set as default domain senders. I need to send client email and switch them depending if they are users of domain1 or domain2. Because I want the serder email will be noreply@domain1.com and noreply@domain2.com depending on the user. In my settings.py, I have the following configuration: ANYMAIL = { 'MAILGUN_API_KEY': API_KEY_DOMAIN1, 'MAILGUN_SENDER_DOMAIN': SENDER_DOMAIN_1'], } EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' SERVER_EMAIL = noreply@domain1.com DEFAULT_FROM_EMAIL = Domain 1 <noreply@domain1.com> Here is send email code: email = AnymailMessage( to=message.to.split(','), cc=message.cc.split(',') if message.cc else None, bcc=message.bcc.split(',') if message.bcc else None, reply_to=None, subject=message.notification.subject, body=message.notification.body_text, from_email=message.from_email, ) email.attach_alternative(message.notification.body_html, 'text/html') if user.brand['name'] == 'domain2': email.esp_extra = { 'sender_domain': SENDER_DOMAIN_2, 'api_key': API_KEY_DOMAIN2, } try: email.send() except Exception as e: print('Error sending email:', e) As you can see. I try to use esp_extra to switch between sender domain, but I get: anymail.exceptions.AnymailRequestsAPIError: Mailgun API response 401 (Unauthorized): 'Forbidden' What could be causing this issue, and how can I resolve it? -
Video Not Displaying on Vercel Deployment in Django Project (Works Locally)
I'm working on a Django project where I'm displaying a video using the tag. The video works perfectly on my local development server, but once I deploy the project to Vercel, the video does not load. Here’s the HTML code I’m using to display the video: I tried using both {{ video_url }} and the {% static %} tag to load the video file from the static/videos directory. I also ensured the video file was collected using collectstatic and updated the vercel.json file to serve static files correctly. I expected the video to load and play as it does on the local development server. However, after deploying to Vercel, the video doesn’t show up at all. No error messages are shown in the browser console. -
Django Filter __In Preserve Order
This question is regarding Django filtering, with __In clause. Basically, I am trying to understand how to filter by providing videos.filter(video__in = video_ids) with string ids, so that each row that gets returned has the same order as the order of string ids in the list used for filtering. For more context, filtering is done using string ids for e.g. ['7C2z4GqqS5E','kTlv5_Bs8aw','OK3GJ0WIQ8s','p8npDG2ulKQ','6ZfuNTqbHE8']. Model video field is video id described above. It is different from the integer id. The video_id_order used below was something I had tried that gave error Field 'id' expected a number but got '7C2z4GqqS5E', I believe this is not being used correctly, and something is still missing to get the order of results preserved as it is in video_ids. What should be the correct order function in this case or is this approach even correct with Django models to preserve query-set result when __In clause is used? def get_video_objects(video_ids,count): ''' video_ids are already in the correct order, filter should return rows in the same order ''' videos = Video.objects.all() // video_id_order = Case(*[When(id=id, then=pos) for pos,id in enumerate(video_ids)]) results = videos.filter(video__in = video_ids) // results = results.order_by(video_id_order) results = list(results[:int(count)]\ .values('video','title','comment_count','likes')) return results Video model is as following … -
DRF: The registration token is not a valid FCM registration token in the first time i send noti
After technical login, the first notification will return the same response enter image description here But from the time I sent it onwards, everything was fine enter image description here This is my scripts class SendServiceOrderView(APIView): def post(self, request): serializer = SendServiceOrderSerializer(data=request.data) serializer.is_valid(raise_exception=True) service_order, technicians, invalid_technician_ids = self.get_order_data(serializer) devices = FCMDevice.objects.filter(user__in=technicians) service_order_data = service_order_service.get_by_id(service_order) serialized_order = FBServiceOrderSerializer(service_order_data) response_data = self.send_notifications(devices, serialized_order.data) response_data["failed_technical_ids"] = list(invalid_technician_ids.union( set(technicians.values_list('id', flat=True)) - set(devices.values_list('user_id', flat=True)) )) return Response(response_data, status=status.HTTP_200_OK if devices else status.HTTP_404_NOT_FOUND) def get_order_data(self, serializer): return ( serializer.validated_data['service_order'], serializer.validated_data['technicians'], serializer.validated_data['invalid_technician_ids'] ) def send_notifications(self, devices, order_data): response_data = {"message": "Notification sent to %d devices." % devices.count()} if devices: try: for device in devices: device.send_message(Message( token=device.user.fcm_token, notification=Notification( title='Find new work', body=order_data['service']['name'] ), data = { "data": json.dumps(order_data) } )) except Exception as e: response_data["errors"] = str(e) else: response_data["message"] = "No valid devices found for the specified technicians." return response_data I hope the first's reponse same the second -
Django quiz system: how to let system save the student answer and calculate the mark before go to another question
below is code from views.py def random_view(request, aid): assignment = get_object_or_404(Assignment, aid=aid) questionbank = Questionbank.objects.filter(assignment=assignment) # Create a paginator object paginator = Paginator(questionbank, 1) # Show 1 question per page # Get the page number from the request's GET parameters page_number = request.GET.get('page', 1) # Get the Page object for the current page page_obj = paginator.get_page(page_number) context = { 'assignment': assignment, 'page_obj': page_obj, } return render(request, 'random_exam.html', context) below is the code from models.py from django.db import models # Create your models here. class Account(models.Model): Area_Level = ( (0, 'student'), (1, 'lecturer') ) id = models.AutoField(primary_key=True) username = models.CharField(max_length=225, null=False, verbose_name="username") email = models.EmailField(max_length=50, null=False, verbose_name="email") password = models.CharField(max_length=512, null=False, verbose_name="password") customer_type = models.IntegerField(default=0, choices=Area_Level, verbose_name="customer_type") class Assignment(models.Model): mechanism_Level = ( (0, 'random'), (1, 'fixed') ) aid = models.AutoField(primary_key=True) assignment_name = models.CharField(max_length=255) mechanism_type = models.IntegerField(default=0, choices=mechanism_Level, verbose_name="customer_type") time = models.IntegerField() def __str__(self): return "%s" %(self.assignment_name) class Meta: db_table="Assignment" class Questionbank(models.Model): assignment = models.ForeignKey(Assignment,on_delete=models.CASCADE, default=1) qid = models.AutoField(primary_key=True) question = models.CharField(max_length=255) option1 = models.CharField(max_length=255) option2 = models.CharField(max_length=255) option3 = models.CharField(max_length=255) option4 = models.CharField(max_length=255) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) level = models.CharField(max_length=10, choices=(('easy', 'easy'), ('middle', 'middle'), ('hard', 'hard'))) score = models.IntegerField() def __str__(self): return "<%s:%S>" %(self.assignment,self.question) class Meta: db_table="Questionbank" class StudentAnswer(models.Model): student = models.ForeignKey(Account, on_delete=models.CASCADE, … -
How to retrieve object ids present in a form at POST request processing time
I have a Django form that contains a table with rows that reflect course objects from a database . Each row contains a checkbox input . When the form is submitted , I want to update which courses are checked and unchecked into the user profile. To do that I need to know which inputs are checked , which I know how to retrieve, but I also need to know which inputs are unchecked . This is not as easy as ‘all the others’ because my table does not always contain all course objects from the database. Its often a filtered set. So I need to know which courses are present in the table. Of course I know this at rendertime, but I dont know how to retrieve it at POST request processing time. I have been researching but am unsure about the best way to solve this problem. I read something about using hidden inputs , which I could give a try. The idea would be to give each row a hidden input with the course id, which I could retrieve when the form is submitted. I am curious if this would be the way to go. Or if … -
WebSocket disconnected with code: 1011 in django
consumers.py import asyncio import websockets import sounddevice as sd import vosk import queue from channels.generic.websocket import AsyncWebsocketConsumer model_path = "vosk_model/vosk-model-small-en-us-0.15" model = vosk.Model(model_path) sample_rate = 16000 audio_queue = queue.Queue() class SpeechRecognitionConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() self.rec = vosk.KaldiRecognizer(model, sample_rate) print("WebSocket connection accepted") async def receive(self, bytes_data): audio_queue.put(bytes_data) await self.process_audio() async def process_audio(self): while not audio_queue.empty(): data = audio_queue.get() if self.rec.AcceptWaveform(data): result = self.rec.Result() result_dict = json.loads(result) recognized_text = result_dict.get('text', '') print("recognized_text: ", recognized_text) print("Final Result: ", recognized_text) await self.send(text_data=json.dumps({ 'type': 'result', 'text': recognized_text })) else: partial_result = self.rec.PartialResult() partial_dict = json.loads(partial_result) partial_text = partial_dict.get('partial', '') print("Partial Result: ", partial_text) await self.send(text_data=json.dumps({ 'type': 'partial', 'text': partial_text })) async def disconnect(self, close_code): print(f"WebSocket disconnected with code: {close_code}") audio.py import asyncio import websockets import sounddevice as sd async def send_audio_data(websocket): loop = asyncio.get_event_loop() def audio_callback(indata, frames, time, status): if status: print(f"Audio Status: {status}") audio_data = bytes(indata) print(f"Received audio data of length: {len(audio_data)}") asyncio.run_coroutine_threadsafe(websocket.send(audio_data), loop) with sd.RawInputStream(samplerate=16000, channels=1, dtype='int16', blocksize=1024, callback=audio_callback): print("Recording and sending audio data...") while True: await asyncio.sleep(0.05) async def main(): uri = "ws://localhost:8000/ws/recognize/" async with websockets.connect(uri) as websocket: print("Connected to WebSocket server") await send_audio_data(websocket) # Create an event loop loop = asyncio.get_event_loop() loop.run_until_complete(main()) I'm developing a speech recognition feature in … -
JQuery editable select after Ajax call in Django
I'm using JQuery editable select in a Django project to make select widgets searchable. When I'm calling another template containing selectboxes with Ajax, the script won't apply unless I use : $.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js").then(() => {} The problem is that it makes the rendering of the Ajax very slow and random. Is there a way to cache the script in the parent template and load it only once so I can reuse it when I'm rendering the child template ? Here is my AJAX call on parent template : $.ajaxSetup( { data: {select_update_record_project_id: sales_documents_id , csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "GET", url: "/my_url/", cache: true, // I have tried both true and false beforeSend: function(){ $('#div_master_sales_documents_edit').empty() }, success: function (data) { $.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js").then(() => { $("#div_master_sales_documents_edit").html(data); }); } }); } Here is my child template rendered after Ajax call : <select id="sales_documents_editable_select_description_1"></select> <select id="sales_documents_editable_select_description_2"></select> <select id="sales_documents_editable_select_description_3"></select> <script> // this is where you apply the editable-select to select widgets var list_selectbox_ids = ['sales_documents_editable_select_description_1','sales_documents_editable_select_description_2','sales_documents_editable_select_description_3']; for (let i = 0; i < list_selectbox_ids.length; i++) { $('#' + list_selectbox_ids[i]).editableSelect({effects: 'fade'}).on('select.editable-select', function (e, li) { populate_sales_documents_selected_product($('#' + list_selectbox_ids[i]).attr('id'), li.text(), li.val()) }); } </script> -
How to handle multiple products in a sale with instalment payments in Django/MySql?
I'm building an inventory management system using Django where clients can purchase multiple products in different quantities as part of a single sale. The client may also pay for the sale in installments, rather than paying for each product individually. Current Tables/Models: Client: Records first name last name and the type of the client (e.g enterprise or regular person). Product: Records name and stock unit that describes the quantity of this product and a description of the item. Sell: Records sales. Buy: Records product buyings (e.g restocking) Payment: Records client payments. The issue: I need a way to: Allow the client to make payments in installments for the total sale price. Update the status of the sale ("pending" or "completed") based on whether the client has fully paid for the sale. Track the whole sale instead of relying on each product. Current models: class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() stock_unit = models.PositiveIntegerField() created_at = models.DateTimeField(default=timezone.now) numero_bl = models.CharField(max_length=30,null=True, blank=True) def __str__(self): return self.name # ----------------------------------------------------------- class Client(models.Model): CLIENT_TYPE_CHOICES = [ ('particulier','Particulier'), ('entreprise','Entreprise'), ] first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) client_type = models.CharField( max_length=20, choices=CLIENT_TYPE_CHOICES, default='particulier' ) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.first_name} {self.last_name} ({self.client_type})" # ----------------------------------------------------------- class … -
django admin Unknown error for user registration
When I added USER to admin and then registered and created a new class for his admin, Django showed me this error. from django.contrib import admin from .models import * class CategoryAdmin(admin.ModelAdmin): list_display = ("name",) class JobAdmin(admin.ModelAdmin): list_display = ("id", "title", "description", "salary", "created_at", "updated_at", "category") class UserAdmin(admin.ModelAdmin): list_display = ("id", "name", "lastname", "country", "age") admin.site.register(Category, CategoryAdmin) admin.site.register(Job, JobAdmin) admin.site.register(JobUser, UserAdmin) I wanted to add a new column User in my admin to see and manage him. -
how can i make many to many relationship between my two models successfully in my project in django?
after i made aproject by flask and sqlite iwant to make it by django i succeeded in adding foods to certain date and calculates the total calories but i fail to show the days with total calories in the home page i show only the days that i added to my model but can not show its detail from total protein and fats and calories so i want asoluation in create_date function in my view and here is my project details first my model from django.db import models from datetime import datetime # Create your models here. class Food(models.Model): name=models.CharField(max_length=512,unique=True) protein=models.IntegerField(null=False) carbohydrates=models.IntegerField(null=False) fats=models.IntegerField(null=False) calories=models.IntegerField(null=True) def total_calories_food(self): total=self.protein * 4 + self.carbohydrates * 4 + self.fats * 9 self.calories=total self.save() def __str__(self): return f'{self.name}' class Dates(models.Model): food=models.ManyToManyField(Food,through='DatesFoods') date=models.DateField() class DatesFoods(models.Model): date_id=models.ForeignKey(Dates,on_delete=models.CASCADE) food_id=models.ForeignKey(Food,on_delete=models.CASCADE) second my forms: from django import forms from .models import Food, Dates class Food_Form(forms.ModelForm): class Meta(): model = Food fields = ('name', 'protein', 'carbohydrates', 'fats') class Dates_Form(forms.ModelForm): class Meta(): model = Dates fields = ('date',) and finally my views def create_date(request): form=Dates_Form(request.POST) dates = Dates.objects.all() if form.is_valid(): form.save() return render(request,'foodlist/home.html',context={'form':form,'dates':dates, }) def add_food(request): form=Food_Form(request.POST) if form.is_valid(): form.save() foods=Food.objects.all() for d in foods: d.total_calories_food() return render(request,'foodlist/add_food.html',context={'form':form,'foods':foods}) def view_foods_day(request,date): d=get_object_or_404(Dates,date=date) print(d) …