Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static Files Not Loading through IIS
Currently I am stuck with deployment of Django on IIS as static files are not loading ...I tried to collect all staticfiles via command python manage.py collectstatic and then make virtual directory under my website Here is hirarchy of my project under IIS Under settings file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Please tell me what I am doing wrong? I tried through configuring virtual directory under my project -
Which scripting language can be a good choice to make a video streaming website
Which backend language should i use : django ,flask or php to make mini movie streaming website ? I have so much experience with php and I want to try a different project a streaming website like Netflix then which backend framework should i use ? (Django ,php ,flask) -
Page not found (404) “/app/media/products/23/05/01/jeans.jpg” does not exist in django
Page not found (404) “/app/media/products/23/05/01/jeans.jpg” does not exist while delpolying on railway (as i have turned debug on for the exact error) . i get this error when i am trying to open my image in new tab,it is not showing after deployment on railway,i have uploaded image after deploying on https://web-production-08528.up.railway.app/admin/ it is working fine when i am using localhost settings.py DEBUG =True #DEBUG = config('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['web','127.0.0.1:8000'] # Application definition INSTALLED_APPS = [ 'shop', 'cart', 'orders', 'payment', 'phone_field', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myshop.urls' STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS=[ BASE_DIR.joinpath('static') ] DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' CART_SESSION_ID='cart' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static admin.site.site_header = 'Admin Panel' urlpatterns = [ path('admin/', admin.site.urls), path('cart/',include('cart.urls',namespace="cart")), path('orders/',include('orders.urls',namespace='orders')), path('payment/',include('payment.urls',namespace='payment')), path('',include('shop.urls',namespace="shop")), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)``` -
Redirect back to previous page with a dataobject
I'm building a webapp with Django, Vue und Inertia. I'm searching for a possibility to redirect to the last page after a POST/PATCH request potentially with an object of errors. In Laravel you can write '''return redirect()->back()->withErrors(...)'''. How can I implement this functionality with django-inertia? -
How to import huge time series data from (DRF) to user interface (UI)
How to import huge time series data from (DRF) to user interface (UI) Hello, I am fetching data from Redis TimeSeries using the mrange command, and it returns data of around 4-5MB in size. I need to transfer this large data to the UI, but I don't know how to handle such a large dataset. I tried splitting it into smaller chunks, but in React, when the data arrives in chunks, it triggers a re-render for each data point, resulting in too many renders per second, which is not desirable. How can I transfer such a large dataset efficiently -
Sending JSON data via GET method in Django API but not receiving it in backend
I am trying to create an API in Django. I am sending json data via get method but not receiving data in backend. I tried send data through requests.get(url, json={"query":"Hello"}) method, Same should be received in django backend. client.py import requests endpoint = "http://127.0.0.1:8000/api" response = requests.get(endpoint,json = {"query":"Hello"}) print((response.text)) print(response.json()['Message']) print(response.status_code) views.py import json from django.http import JsonResponse def api_home(request, *args, **kwargs): # request --> HttpRequest -->Django print(dir(request)) body = request.body print(body) # byte string of JSON Data print("Request Received.....") print("Responding.....") return JsonResponse({"Message" : "Hi there, this is your django api response"}) Output in Client.py terminal {"Message": "Hi there, this is your django api response"} Hi there, this is your django api response 200 Output at Server Side b'' Request Received..... Responding..... -
Automatically push the code on the server when the remote github repository is updated
Automatically fetch the code on server from Github when the repository is updated on Github I have deployed my project on server. There are more multiple contributors in this project now, so we make changes in our local machine and then push those changes on the github. How can I create a workflow where every time the github repository is updated with latest push from local repository, the repository on my server also get those changes automatically? Does git have any feature to do that? -
WebSocket chat application not displaying sent message, but refreshing the page instead
I was building a web app to send messages using django.I could not Figure out why this part of the code isnt working,When I type the message and hit send, It just refreshes the page without displaying the message.I even tried inspecting the code in chrome dev tools,but nothing has been displayed on the console suggesting that the javascript code isnt working. ` const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); let url = 'ws://${window.location.host}/ws/${roomName}/' const chatSocket = new WebSocket(url); chatSocket.onclose = function(e) { console.log('onclose') } chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.message) { document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + '</b>: ' + data.message + '<br>'); } else { alert('The message was empty!') } scrollToBottom(); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { e.preventDefault() const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; console.log({ 'message': message, 'username': userName, 'room': roomName }) chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, 'room': roomName })); messageInputDom.value = ''; return false }; /** * A function for finding the messages element, and scroll to the bottom of it. */ function scrollToBottom() { let objDiv = document.getElementById("chat-messages"); objDiv.scrollTop = objDiv.scrollHeight; } // Add this below the … -
How do I fix 'Module social_core.backends.google does not define a GoogleOpenId attribute/class' error in Django login?
I pulled the old my Django project but when I login, I got the following error. Module "social_core.backends.google" does not define a "GoogleOpenId" attribute/class I searched this error but I can't find any solution. -
Docker giving error django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution
I am trying to dockarize my django app but I have a problem in configuring the database: docker-compose.yaml: services: db: image: postgres:13 container_name: db # networks: # - djangonetwork volumes: - postgres_data:/var/lib/postgresql/data/ environment: # - POSTGRES_HOST_AUTH_METHOD=trust - "POSTGRES_NAME=postgresa" - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres es: image: elasticsearch:7.9.1 environment: - xpack.security.enabled=false - discovery.type=single-node ports: - "9200:9200" - "9300:9300" networks: - elastic volumes: - ./data/elastic:/var/lib/elasticsearch/data web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" environment: - POSTGRES_NAME="postgres" - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - .:/app # - /tmp/app/mysqld:/run/mysqld depends_on: - db - es networks: - elastic # - postdata # links: # - es:es # networks: # - djangonetwork thesearchable: build: ./thesearchable ports: - "3000:3000" volumes: - ./frontend:/frontend volumes: postgres_data: networks: elastic: driver: bridge in settings.py: 'default': { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } I have found that many people faced this problem but none of the answers solved my problem and I always find this message error django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution so how can I solve this? -
Unable to download Pillow
I keep getting this error with "Failed to building wheel for pillow" and "Could not build wheels for pillow, which is required to install pyproject.toml-based projects". PS C:\Users\sneha> pip3 install pillow Collecting pillow Using cached Pillow-9.5.0.tar.gz (50.5 MB) Preparing metadata (setup.py) ... done Building wheels for collected packages: pillow Building wheel for pillow (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [189 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-310 creating build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\Image.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ImageChops.py -> build\lib.mingw_x86_64-cpython-310\PIL copying … -
external script from views.py with Pandas
I am trying to execute a script that uses Pandas external from views.py in Django. I have tried all the solutions that I have found here, but I continue to receive this message: ModuleNotFoundError: No module named 'pandas' while Padas is correctly installed and it works fine. If I run the script from the terminal it works, Panda from views.py works, but not from the external file (prova.py). ##views.py def external(request): path = 'D:\Django_Progetti(miei)\TEST_rinfresco\gestionecontatti\contatti\management\commands\prova.py' out = subprocess.run(['python', path], stdout=subprocess.PIPE) output = out.stdout.decode('utf-8') return HttpResponse(output) ##prova.py import pandas as pd print("Example") -
UnboundLocalError: local variable 'current' referenced before assignment
I'm using django to aggregate averages, sums, etc, of a queryset and have the code below. What I expect is that the case matches the period and then the sum and average is computed further down the code but I get the error: UnboundLocalError: local variable 'current' referenced before assignment def metrics(request): email = request.data.get("email") period = request.data.get("period") # [0,1,2,3 : day, week, month, year] today = date.today() weekday = date.isoweekday(today) month = today.month year = today.year current_week = date.isocalendar(today).week store = Store.objects.get(account__email=email) sales = Order.objects.filter(store=store) match period: case 0: # 'Today' current = sales.filter(created__week_day=weekday) past = sales.filter(created__week_day=weekday - 1) case 1: # 'This week' current = sales.filter(created__week=current_week) past = sales.filter(created__week=current_week - 1) case 2: # 'This month' current = sales.filter(created__month=month) past = sales.filter(created__month=month - 1) case 3: # 'This year' current = sales.filter(created__year=year) past = sales.filter(created__year=year - 1) current_total = current.aggregate(Sum('products_total'))['products_total__sum'] past_total = past.aggregate(Sum('products_total'))['products_total__sum'] current_average = current.aggregate(Avg('products_total'))['products_total__avg'] past_average = past.aggregate(Avg('products_total'))['products_total__avg'] current_count = current.count() past_count = past.count() Printing the values, I get: # today: 2023-05-20 # weekday: 6 # month: 5 # year: 2023 # current week: 20 products_total is a field in my model but I don't think is relevant to the question: class Order(models.Model): products_total = models.DecimalField(max_digits=10, decimal_places=2, … -
Failed to dockerize my django app with elasticsearch
I was working with django and elasticsearch in the same app and everything was working good until I decided to dockerize the whole app as It when I run docker exec -it 4b93cbdacf84 python manage.py search_index --rebuild it give me a response: elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9b532c8940>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9b532c8940>: Failed to establish a new connection: [Errno 111] Connection refused) docker-compose.yaml: services: db: image: postgres:13 container_name: db # networks: # - djangonetwork volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" es: image: elasticsearch:7.9.1 environment: - xpack.security.enabled=false - discovery.type=single-node ports: - "9200:9200" - "9300:9300" networks: - elastic volumes: - ./data/elastic:/var/lib/elasticsearch/data web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - .:/app # - /tmp/app/mysqld:/run/mysqld depends_on: - db - es networks: - elastic thesearchable: build: ./thesearchable ports: - "3000:3000" volumes: - ./frontend:/frontend volumes: postgres_data: networks: elastic: driver: bridge documents.py from django_elasticsearch_dsl import Document, fields, Index from django_elasticsearch_dsl.registries import registry from django.conf import settings from .models import * from elasticsearch_dsl import analyzer, tokenizer autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'ngram', min_gram=1, max_gram=20), filter=['lowercase'] ) entry_index=Index('entries') # See Elasticsearch Indices API reference for available settings … -
accessing Django models through external Domain
I have a project structure as following: mainFolder |- djangoFolder manage.py mainApp (package) |- Domain Facade ... mainApp imports Facade I'm trying to access the ORM features like Model.objects.create(...) from the Facade but I encountered a few errors when doing so. I added the following to one of the objects that the Facade holds: import os import django os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "djangoFolder.mainApp.settings" ) django.setup() this change throws : RuntimeError: populate() isn't reentrant which means im calling django.setup() twice in the same context (because mainApp imports Facade) then I tried removing django.setup() which throws : django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. looked for solutions on the internet/gpt and haven't found one. any idea how to fix it? -
Graphene Django with SerializerMutation requires foreign key field's id to be passed as a string
I have two models Category and Item as follows class Category(models.Model): name = models.CharField(max_length=100) class Meta: db_table = 'categories' def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey('Category', on_delete=models.DO_NOTHING, null=True, blank=True, related_name='related_items') class Meta: db_table = 'items' def __str__(self): return self.name and I have simple Mutation classes which I have created as follows which subclasses SerializerMutation from graphene_django.rest_framework.mutation import SerializerMutation class CategoryMutation(SerializerMutation): class Meta: serializer_class = CategorySerializer model_operation = ['create', 'update'] lookup_field = 'id' class ItemMutation(SerializerMutation): class Meta: serializer_class = ItemSerializer model_operation = ['create', 'update'] lookup_field = 'id' class Mutation(graphene.ObjectType): cud_category = CategoryMutation.Field() cud_item = ItemMutation.Field() My serializers are also simple ModelSerializers which are as follows: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['id', 'name'] class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['id', 'name', 'category'] Now I am able to perform a create mutation for Category as below THE QUERY mutation{ cud_category(input:{name: "category_1"}) { id name } } and get a return as follows THE OUTPUT { "data": { "cud_category": { "id": 30, "name": "category_1" } } } Now when I try creating an Item as follows ---> Here is where the issue starts THE QUERY mutation{ cud_item(input:{name: "item_1" category: 30}) { id … -
How do i fix this error "Reverse for 'poll_details' with arguments '('',)' not found."
I mistakenly deleted the db.sqlite3 file in my django project and i tried running python manage.py migrate to make a new one but it didnt work. I finally got it to work with python manage.py migrate --run-syncdb. The problem now is when i run the server and try to visit the homepage(which used to be populated with polls from the former db), I get this error Reverse for 'poll_details' with arguments '('',)' not found. 1 pattern(s) tried: ['poll/(?P<question_id>[0-9]+)$'] Since I don't have anything in my db anymore(yet) I thought I should be expecting a blank page. This is my index view which renders the index page def index(request): user = request.user if user.is_authenticated: return HttpResponseRedirect(reverse("poll:home")) latest_questions = Question.objects.order_by("-pub_date")[:10] return render(request, "poll/index.html", {"questions": latest_questions}) This is index template {% block body %} <h1> Polls </h1> <ol> {% for question in questions %} {% empty %} <p> There are no polls yet</p> <li>{{ question }}</li> <a href="{% url 'poll:poll_details' question.id %}"> View Poll </a> {% endfor %} </ol> {% endblock %} -
Django Rest Framework retrieving object details returns "Not found" when utilizing MPTT and UUID as object's ID
Facing an issue "Not found" with combination of DRF model with UUID field and MPTT. I have a simple api with only one app "categories" (imitation of e-shop categories). models.py: class Category(MPTTModel): objects = CategoryManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=120, db_index=True, unique=True) slug = models.SlugField(unique=True) description = models.TextField(null=True, blank=True) parent = TreeForeignKey( "self", blank=True, null=True, related_name="child", on_delete=models.CASCADE ) is_active = models.BooleanField(default=True) class Meta: verbose_name_plural = 'categories' def get_absolute_url(self): return f"/products/{self.slug}/" def __str__(self) -> str: return self.name Then I faced a problem: when tried to get a list of all objects (root endpoint) all children were duplicated (first in a child field of a parent and then as an individual object down below). So I modified MPTT TreeManager adding a method : class CategoryManager(TreeManager): def viewable(self): queryset = self.get_queryset().filter(level=0) return queryset It solved a problem. But now when I try to get a single object detail I get {"detail": "Not found"} except a parent object. Is there any way to keep displaying all objects withot duplacating and still be able to acces a single object's details? views.py: class CategoriesAPIViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer lookup_field = 'slug' # permission_classes = (IsAuthenticated,) serializers.py: class CategorySerializer(serializers.ModelSerializer): child = RecursiveField(many=True, … -
Django passing values from views to html
I have two pages for reserving a table in a restaurant, and their logic is as follows: on the first page, the user enters their contact details, reservation date, and number of guests, and then clicks the "Next" button. They are then redirected to the second page, where they need to select a table and time (the available time slots are generated based on the selected date). The problem is that I can't pass the time values to the template of the second page through the view. Here's a rough example of the code: def contact_details(request): if request.method == 'POST': # Get the form data from the request # ... # Store the form data in the session request.session['client_name'] = client_name request.session['client_email'] = client_email request.session['client_phone'] = client_phone request.session['number_of_guests'] = number_of_guests request.session['reservation_date'] = reservation_date request.session['reservation_time'] = [str(time) for time in free_time()] return redirect('reservation_data') return render(request, 'contact_details.html') def reservation_data(request): if request.method == 'POST': # Get the form data from the session # ... # Create the reservation using the form data # ... # Clear the session data request.session.clear() return redirect('reservation_detail', pk=reservation.pk) return render(request, 'reservation_data.html') I understand that values are typically passed to the template using render, but if I use render … -
How to access html+js canvas in Django?
I tasked myself to write a website in python using django. The website contains a canvas where you can draw with a mouse. Now I need to get the pixel values of the canvas and somehow "send them to python", so that my neural network can process this image. How can I do that? {% extends 'main/layout.html' %} {% block title %}Anton{% endblock %} {% block content %} <div class="features"> <h1>{{title}}</h1> <p>{{ current_url }}</p> <canvas id="canvas">Canvas</canvas> <script src="/static/main/js/drawing.js"></script> <!-- <button class="btn btn-warning">To page about us</button>--> </div> {% endblock %} var isMouseDown = false, canv = document.getElementById('canvas'), ctx = canv.getContext('2d'), brushThickness = 10; canv.width = 600; canv.height = 600; ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canv.width, canv.height); ctx.fillStyle = 'black'; ctx.lineWidth = brushThickness * 2 canv.addEventListener('mousedown', function() { isMouseDown = true; }); canv.addEventListener('mouseup', function() { isMouseDown = false; ctx.beginPath(); }); canv.addEventListener('mousemove', function(e) { if (isMouseDown) { var rect = canv.getBoundingClientRect(), x = e.clientX - rect.left, y = e.clientY - rect.top; ctx.lineTo(x, y); ctx.stroke(); ctx.beginPath(); ctx.arc(x, y, brushThickness, 0, Math.PI * 2); ctx.fill(); ctx.beginPath(); ctx.moveTo(x, y); } }); document.addEventListener('keypress', function(event) { if (event.key === 'q') { var imageData = ctx.getImageData(0, 0, canv.width, canv.height); var pixels = imageData.data; console.log(pixels); } }); from django.shortcuts import … -
Error sending audio.wav file from React to Django
I'm working on building a transcription app using React and Django. I'm trying to figure out how to play the audio that is uploaded to my server. I'm able to record and send the audio on React using react-media-recorder but once it gets to backend, I get an error in VS code that reads 'An error occurred while laoding the audio file.' It's weird. The error is not appearing in my server dialogue. At first I thought it was my views.py file, but I'm starting to think it's a different problem. Here is my views file from django.shortcuts import render from rest_framework.views import APIView from . models import * from . serializer import * from rest_framework.response import Response from django.http import JsonResponse # Create your views here. class AudioUploadView(APIView): def get(self, request): output = [{"upload": output.file} for output in Audio.objects.all()] return Response(output) def post(self, request): print('hello', request.data.get('audio')) audio_blob = request.data.get('audio') # save file to path with open('audio.wav', 'wb') as audio_file: for chunk in audio_blob.chunks(): audio_file.write(chunk) return JsonResponse({'message': 'New audio uploaded'})# convert audio to .wav file The output is 'hello, audio.wav' Here is my model file. I realize this could possibly be a problem with how my models are working, too. … -
Retrieve object associated in field based on logged in user Django
I have only two models: class Game(models.Model): player1 = models.ForeignKey('Player', related_name='player1' #other details) player2 = models.ForeignKey('Player', related_name='player2' #other details) player3 = models.ForeignKey('Player', related_name='player3' #other details) class Player(models.Model): owner = models.ForeignKey(User, #other details) art = models.URLField() VIEW: Once a user submits a link (custom validation in place) via a form, my view creates a Player object and then creates a Game object (if a Game object doesn't exist or is "full" because all player fields are populated) or it updates the next empty player1, player2, or player3 field by associating the newly created Player instance with it. That works fine, but I'm stuck on how to query something for the next view/template. QUESTION: I want to display a Game object to a User who is logged in based on if they are a Player object associated with either player1, player2, or player3. I don't want it to display just a recent Game object -- say using something like Game.objects.latest() -- because that might not be the one the User is associated with if other Game objects were created. I cannot figure out how get the correct Game object. Best I can do is get the Player object associated with the User … -
Updating the same data in a cluster may cause coverage issues
enter image description hereAs shown in the figure when different servers in my web cluster operate on the same data, it may result in data coverage. How should I handle this problem? I know that if there is only one server, locking this part in the business logic is sufficient, but now it is a service cluster, locking cannot limit this behavior Or how should we set up reasonable logic in the face of this situation I have tried to set an inaccessible identifier for the current data when operating on the front-end page. But the same problem occurred when setting identifiers My backend service uses Django, and for a single server, I use with transaction. atomic() to prevent problems from occurring If it's a server cluster, I'm not sure what to do. I have little experience in this area. Can someone help me -
Django How to get value of CheckboxSelectMultiple in Javascript in Template
I have a CheckboxSelectMultiple in a Django form like this : forms.py LIST= [ ('Oranges', 'Oranges'), ('Cantaloupes', 'Cantaloupes') ] testrever = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelectMultiple(choices=LIST)`) I would like to get the Checkboxes value, each time that one of them is there is selected / unselected to populate another field of the form (email). This is what I got so far but I can't retrieve the chekboxes value : template.py <script> $(function(){ $('#id_testrever').change(function(){ var a = $("#id_email").val(); if ($("#id_testrever").val() == "Oranges") $("input[name=email]").val(a + "Oranges") if ($("#id_testrever").val() == "Mangoes") $("input[name=email]").val(a + " Mangoes") }); }); </script> -
a weired pop up on django in django admin panel
After a long time, i returned to my django project only to encounter a perplexing issuea persistent pop-up appearing not only on the login page but also within the admin panel. Initially, i suspected missing static files as the culprit. To investigate further, i enabled debug mode by setting debug = true in my project's settings, hoping to gain more insights. Disappointingly, the pop-up problem persisted, despite my efforts. Given the brevity of my description, it is difficult to pinpoint the exact source of this vexing pop-up. Nonetheless, i can suggest a few potential troubleshooting steps to help resolve the issue. First and foremost, it is crucial to double-check the availability and correct configuration of all essential static files. Carefully review the linkage of static files within your django project, ensuring that they are properly accessible within the admin panel. Another possibility is that the pop-up is triggered by a javascript error or conflict within the admin interface. It would be helpful to inspect the browser console for any javascript errors and carefully examine the javascript code in your project, particularly custom scripts or modifications you have made. If the pop-up persists despite these initial checks, it might be worth …