Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running DRF endpoints in a venv with gunicorn
I have some APIs implemented with DRF and I want those to run in a venv. I am using gunicorn. I run gunicorn like this: /path_to_venv/bin/gunicorn But in the API code I log os.getenv('VIRTUAL_ENV') and it's None. Is that valid evidence that the code is not running in the venv? If so, how can I force it to run in the venv? If not, how can I validate that it is running in the venv? -
Extract Musical Notes from Audio to array with FFT
I'm trying to create a project in which I upload an audio file (not necessarily wav) and use FFT endpoint to return an array with the names of the sounds. Currently, I have such code, but even though I upload a file with only the sound A, it receives the value E-10, and when uploading, for example, title, I receive only one sound. Would anyone be able to help me? import os from django.shortcuts import render from django.http import JsonResponse from pydub import AudioSegment import numpy as np from noteQuiz import settings #Names of the notes NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def freq_to_number(f): return 69 + 12*np.log2(f/440.0) def number_to_freq(n): return 440 * 2.0**((n-69)/12.0) def note_name(n): return NOTE_NAMES[n % 12] + str(int(n/12 - 1)) def find_top_notes(fft, xf): if np.max(fft.real) < 0.001: return [] lst = [x for x in enumerate(fft.real)] lst = sorted(lst, key=lambda x: x[1], reverse=True) idx = 0 found = [] found_note = set() while (idx < len(lst)) and (len(found) < 1): f = xf[lst[idx][0]] n = freq_to_number(f) n0 = int(round(n)) name = note_name(n0) if name not in found_note: found_note.add(name) s = [note_name(n0)] found.append(s) idx += 1 return found def … -
Django broken pipe error when handling large file
A server developed using the Django framework is hosted in a local environment, and a broken pipe error occurs in the process of processing large files. The current problem is the code below, which is to respond by changing the DICOM file to the png extension through a separate view to deal with the DICOM file. There is no problem in normal cases, but a broken pipe error occurs when processing about 15MB of files. # javascript code for request file data in html template function loadImages(images, fileType, index) { event.preventDefault(); if (index < images.length) { var image = images[index]; var fileName = image.image_url.split('/').pop(); var imageData = { fileName: fileName, }; imageInfoArray.push(imageData); var img = new Image(); img.onload = function() { var filePreviewHTML = ` <li class="add-image-${index}"> <a href="javascript:void(0)" class="img-wrap" data-id="${index}"> <img src="${(fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url}" alt="ask-file-img"/> <button class="remove-file" onclick="disableImage('${image.image_url}')"><i class="material-icons">close</i></button> </a> <p class="file-name">${fileName}</p> </li> `; var filePreview = $('.file-preview[data-file="' + fileType + '"]'); filePreview.append(filePreviewHTML); loadImages(images, fileType, index + 1); } img.src = (fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url; } // view code for handling DICOM file def show_dicom(request, file_path): file_path = os.path.join(settings.MEDIA_ROOT, "xray_images", file_path) dicom = pydicom.dcmread(file_path) image_array = apply_voi_lut(dicom.pixel_array, dicom) image_array_2d = image_array[0] if … -
Flutter Web: Assets Not Loading Correctly from main.dart.js Using Current Relative URL Instead of Base HREF
I'm currently working on hosting a Flutter web application using a Django web server on an Ubuntu 20.2 environment. The Flutter version I'm using is 3.13.5, channel stable, and my project structure has the Flutter web project located in the static folder. I've been facing an issue where the Flutter web application cannot locate the FontManifest.json file. It seems like this file is being sought using the current URL (relative) instead of the base URL defined in the index.html file. Assets loaded from index.html work correctly with the base href directed to static directory, but those loaded from main.dart.js and are using the current URL. Has anyone encountered a similar issue or has insights on how to ensure that all assets, including FontManifest.json, loaded from main.dart.js use the base URL as intended? I am almost inclined to reference the missing visual assets in main.dart through the Network module but I think Flutter should have a configuration option to determine the static-uri-location where the app will be hosted with all it's static files instead of just having to rely on the relative-uri for static files. 1.I tried fetching those 2 files (AssetManifest.bin + FontManifest.json) through the main.dart.js but that does not … -
Django not saving data with post
I have this view: class TaskApiView(APIView): def post(self, request): serializer = TaskSerializer(data=request.data) print(request.data) if serializer.is_valid(): print("valid") serializer.save() return Response(status=status.HTTP_201_CREATED) else: print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) request body: { "content": "asd" } log: {'content': 'asd'} valid [21/Oct/2023 11:33:19] "POST /api/task/create HTTP/1.1" 201 0 But when I try to get all tasks with this view class TaskListAPIView(generics.ListAPIView): queryset = Task.objects.all() serializer_class = TaskSerializer I get just the id: [ { "id": 25 } ] Serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" Model id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default="") creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) status: models.CharField( choices=StatusEnum, max_length=5, default=StatusEnum.TODO, ) def __str__(self): return self.id + self.content I want to create a task with content -
how to pass domain name to the container in Container Instances, OCI?
I am running Django application image in container that requires "CSRF_TRUSTED_ORIGINS" to be passed as env variable, but it looks like container instances generate the domain after the deployment; or how can I set the env variable of container DJANGO_CSRF_TRUSTED_ORIGINS="container instance domain" before running the container. -
Getting a 404 error when sending a POST request with APIClient in Django test case
I'm writing a test case for a Django REST Framework API using the APIClient from the rest_framework.test module. I'm trying to send a POST request to the wordOftheDay/ endpoint with the provided data, but I keep getting a 404 error. The server is running and accessible at http://127.0.0.1:8000, and the endpoint is correctly defined in the server's code. I'm not sure what is causing the 404 error in the test case. def test_valid_post_request(self): client = APIClient() print(client) response = client.post('wordOftheDay/', self.valid_data, format='json') print('response',response) self.assertEqual(response.status_code, 200) print('response.status_code',response.status_code) # Check if the model is created with the expected data self.assertTrue(WordModel.objects.filter(device_id=self.valid_data['device_id']).exists()) This is the error - Traceback (most recent call last): File "/home/k/Desktop/project/wordOfTheDay/tests/test_wordOfTheDay.py", line 88, in test_valid_post_request self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 -
How to Save The Form We Created
Form.save not working Hello guys, I created a form myself without using ModelForm self fields to design it on my own by using css and html but at the end form.save not using ı have no idea what to do /////////////////////////////////////////////////////////////////////////////////////////////// This is my view, class ContactView(View): def get(self,request,*args,**kwargs): return render(request,'contact.html') def post(self,request,*args,**kwargs): form = Form(request.POST) if form.is_valid(): newUser = form.save() return redirect('homepage') return render(request,'contact.html',{'form':form}) This is my html, <form method="post"> {% csrf_token %} <div> <h2 style="margin-bottom: 40px; width: 100%; text-align: center;">Get İn Touch</h2> <div><input type="text" placeholder="Name" name="Name"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><input type="text" placeholder="E-mail" name="E-mail"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><input type="text" placeholder="Subject" name="Subject"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><textarea name="" id="" cols="66" rows="10" style="display: block;" placeholder="Message" name="Message"></textarea> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div class="button"> <button type="submit" value="Submit">Send an email</button> </div> </div> </form> this is my form, class Form(forms.ModelForm): Name = forms.CharField(max_length=50) Email = forms.CharField(max_length=100) Subject = forms.CharField(max_length=50) Message = forms.CharField(widget=forms.Textarea) class Meta: model … -
Reverse for 'posts-details-page' with arguments '('',)' not found. 1 pattern(s) tried: ['all_posts/(?P<slug>[-a-zA-Z0-9_]+)$']
I have build the basic Django project but getting error while trying to retrive all the post from the project. you can download the code from github to create the issue, Please guide me how to resolve this issue if anyone can help. https://github.com/techiekamran/BlogProject.git and branch name is starting-blog-project urls.py from django.urls import path from blogapp import views urlpatterns = [ path("",views.starting_page,name='starting-page'), path("posts",views.posts,name="posts-page"), path("all_posts/<slug:slug>",views.post_details,name='posts-details-page'), #posts/my-first-post ] views.py from datetime import date from django.shortcuts import render def get_date(all_posts): return all_posts['date'] def starting_page(request): sorted_post = sorted(all_posts,key=get_date) latest_post = sorted_post[-3:] return render(request,'blogapp/index.html',{'posts':latest_post}) def posts(request): return render(request,'blogapp/all-posts.html',{'all_posts':all_posts}) def post_details(request,slug): identified_post=next(post for post in all_posts if post['slug']==slug) return render(request,'blogapp/post-details.html',{'post':identified_post}) index.html {% extends "_base.html" %} {% load static %} {% block title %} Home {% endblock %} {% block css_files %} <link rel="stylesheet" href="{% static 'blogapp/post.css' %}"/> <link rel="stylesheet" href="{% static 'blogapp/index.css' %}"/> {% endblock %} {% block content %} <section id="welcome"> <header> <img src="{% static 'blogapp/images/max.png' %}" alt="Max= The author of this Blog"/> <h2>Demo blog des</h2> </header> <p>Hi, this is the our first blog</p> </section> <section id="latest-posts"> <h2>My latest thoughts</h2> <ul> {% for post in posts %} {% include 'blogapp/includes/post.html' %} {% endfor %} </ul> </section> <section id="about"> <h2>What I do </h2> <p>I love programming</p> … -
Efficient way of rank update based on points
User_team=User_team.objects.filter().values(), User_team=[{team_id:1, points:50},{team_id:2, points:30},{team_id:3, points:70}] I already migrate New model and key is (rank,point) stored rank and points in this model. User_team_event=User_team_event.objects.filter().values(). I'm expecting answer is without using loops: User_team_event=[{team_id:3,rank:1, points:70},{team_id:1,rank:2, points:50},{team_id:2, points:30}] -
What is the Sever IP Address
Hi sir i have hosted my python application on pythonanywhere and i am using external api which required ip whitelisting for payment processing , I would like to know the sever ip and is it static or dynamic I am unable to locate the sever ip from my dashboard. -
This field is required error in the "Form" class
I have a problem in my form. When I print the error it says "The field is required". can anyone tell me what I am missing. here is my code forms.py: from django import forms class LoginAuth(forms.Form): Email= forms.EmailField() Password= forms.CharField(max_length=300) views.py: from django.shortcuts import render from .forms import LoginAuth def login(request): if request.method=="POST": form = LoginAuth(request.POST) if form.is_valid(): Email= form.cleaned_data['email'] Password= form.cleaned_data['pass'] request.session['user']= Email request.session.set_expiry(2) print("The form is validated") else: print(form.errors) return render(request, "login.html") login.html: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} <input type="email" name="email" placeholder="Enter Email"> <br> <input type="password" name="pass" placeholder="Enter Password"> <br> <br> <input type="submit"> </form> {% endblock %} -
raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
while creating a custom user through the postman api on django im facing this repetedly. please help me to resolve this models.py ROLES = ( (1, 'admin'), (2, 'customer'), (3, 'seller'), ) STATE_CHOICES = ( ('Odisha', 'Odisha'), ('Karnataka', 'Karnataka') ) class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('The email is not given') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.is_active = True user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if not extra_fields.get('is_staff'): raise ValueError('Superuser must have is_staff = True') if not extra_fields.get('is_superuser'): raise ValueError('Superuser must have is_superuser = True') return self.create_user(email, password, **extra_fields) class Roles(models.Model): role = models.SmallIntegerField(choices=ROLES) class Custom_User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=100) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) role = models.ForeignKey(Roles, on_delete=models.CASCADE) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def add_to_group(self): role_instance = self.role group_name = None if role_instance.role == 4: group_name = 'admin' elif role_instance.role == 5: group_name = 'customer' elif role_instance.role == 6: group_name = 'seller' if group_name: group, created = Group.objects.get_or_create(name=group_name) self.groups.set([group]) return self USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role'] objects = UserManager() def __str__(self): return self.email def has_module_perms(self, app_label): return True def … -
no such column: api_task.content during makemigraions
When trying ./manage.py runserver or ./manage.py makemigrations or ./manage.py migrate I am getting: django.db.utils.OperationalError: no such column: api_task.content All solutions say to remove db.sqlite3 remove migrations folder run ./manage.py makemigrations; ./manage.py migrate I did 1 and 2, but when trying to do 3 I get the error above (both commands, along with ./manage.py runserver. I am really confused as to why since, yes, it's obviously missing, but it should get recreated. My aim was to clear the db, and since django recreates the db file, I should be able to just delete and make migrations, but I must be missing smth. Task model: import uuid from django.db import models from django.contrib.auth.models import User class Task(models.Model): id: str = models.UUIDField( unique=True, auto_created=True, primary_key=True, default=uuid.uuid4, editable=False, ) content: str = models.CharField( default="", max_length=255, ) deadline: int = models.IntegerField( default=None, null=True, blank=True, ) creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.id) + str(self.content) -
Django Objects Filter received a naive datetime while time zone support is active when using min max range
So this question is specifically about querying a timezone aware date range with max min in Django 4.2. Timezone is set as TIME_ZONE = 'UTC' in settings.py and the model in question has two fields: open_to_readers = models.DateTimeField(auto_now=False, verbose_name="Campaign Opens") close_to_readers = models.DateTimeField(auto_now=False, verbose_name="Campaign Closes") The query looks like allcampaigns = Campaigns.objects.filter(open_to_readers__lte=today_min, close_to_readers__gt=today_max) Failed Solution 1 today_min = datetime.combine(timezone.now().date(), datetime.today().time().min) today_max = datetime.combine(timezone.now().date(), datetime.today().time().max) print("Today Min", today_min, " & Today Max", today_max) returns the following which would be a suitable date range except it also gives the error below for both min and max. Today Min 2023-10-21 00:00:00 & Today Max 2023-10-21 23:59:59.999999 DateTimeField ... received a naive datetime (9999-12-31 23:59:59.999999) while time zone support is active. Partial Working Solution today_min = timezone.now() allcampaigns = Campaigns.objects.filter(open_to_readers__lte=today_min, close_to_readers__gt=today_min) Returns results without error but the time given is the current time and not the minimum or maximum for the day. Failed Solution 2 from here: now = datetime.now(timezone.get_default_timezone()) today_min = now.min today_max = now.max print("Today Min", today_min, " & Today Max", today_max) Returns Today Min 0001-01-01 00:00:00 & Today Max 9999-12-31 23:59:59.999999 and the aforementioned timezone error. How can I create two timezone aware datetime for the minumum and maximum parts of … -
Django memory Leakage/ less worker
I am working on a project where I have to integrate ML and django together. when running the app there is some lag in compiling and after several minutes i am getting this: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. what is it? how can i solve this? The project should have fetched the data from datasets and then compare the user input and show the result. -
Count of records created in each hour interval starting from midnight to present time
I need to retrieve count of records created in each hour duration from midnight to present time. To do so the model contain a created_at timestamp field which will record the created time. The model definition is given bellow. class Token(models.Model): customer_name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) remarks = models.TextField(null=True,blank=True) modified_at = models.DateTimeField(auto_now =True) The result am looking for like the following in SQL output Intervel | count| -----------------| 01:00 AM | 0 | # 00:00 to 01:00 AM 02:00 AM | 0 | ....... 10:00 AM | 20 | 11:00 AM | 5 | ........ 03:00 PM | 5 | ------------------ I need to get model query that can do the above operation at the database end without loading all the records created in the day since from midnight to now then getting the count by running a forloop in the application. Kindly Help me in this.. -
Field 'id' expected a number but got 'add'
I'm working on a Django project where I have an API endpoint for adding PC parts, and I'm encountering an issue when trying to access the URL /parts/add. I'm getting the following error: ValueError: Field 'id' expected a number but got 'add'. This error seems to be related to my Django model's primary key field, which is an AutoField called 'id.' I'm not explicitly providing an 'id' when adding a new PC part, and I expect Django to generate it automatically. here is my model: from django.db import models # Create your models here. class PCparts(models.Model): id = models.AutoField( primary_key=True) name = models.CharField(max_length=128) type = models.CharField(max_length=50) price = models.DecimalField(max_digits=10, decimal_places=2) release_date = models.IntegerField() # Unix epoch timestamp core_clock = models.DecimalField(max_digits=5, decimal_places=2) boost_clock = models.DecimalField( max_digits=5, decimal_places=2, null=True, blank=True) clock_unit = models.CharField(max_length=5) TDP = models.IntegerField(default=0.0) part_no = models.CharField(max_length=20) class Meta: ordering = ['-price'] def __str__(self) -> str: return self.name here is my view from rest_framework import status from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.db.models import Avg from .models import PCparts from .serializers import partSerializer # Import the serializer class from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.db.utils import IntegrityError # Create your … -
Trouble Sending POST Data for Google Calendar Scheduling in Django: Ajax Newbie
I'm building an app to schedule events on Google Calendar using Django, and I'm encountering an issue with sending data via a POST request to a Django view. Here's my Django view code for CreateEventFunc: from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def CreateEventFunc(request): # For debugging purposes, write data to a file with open('output.txt', 'w') as file: file.write("CreateEventFunc\n") if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) therapist_id = data['therapist_id'] start_time = data['start_time'] end_time = data['end_time'] # Create the event using your utility function (e.g., create_event) # Replace this with your actual implementation created_event = create_event(therapist_id, 'Appointment', start_time, end_time) # Return a response (you can customize this based on your needs) response_data = {'message': 'Event created successfully', 'event_id': created_event['id']} return JsonResponse(response_data) On the frontend, I have a JavaScript function scheduleMeeting that sends a POST request to this view when a meeting is scheduled: <script> function scheduleMeeting(startTime, endTime, therapistId) { if(confirm("Do you want to schedule a meeting from " + startTime + " to " + endTime + "?")) { // Create a data object to send with the POST request var eventData = { 'start_time': startTime, 'end_time': endTime, 'therapist_id': therapistId, }; // Send a POST request to … -
How can I get a django form value and display it back to the user before the form is submitted?
I have done some research...and found a suggestion to create a function on a form to get a field value...get form value I tried this and for some reason I can't get it to work. I've used the clean function on the form as part of the submit process and that works great. The difference here is that I'm essentially trying to inspect the field values well before the form gets submitted. I want the user to click a button and see the values that have been populated in the "approvers" field in this case. I've got the button working...but can't seem to get the "approvers" value to populate. It just shows []. I defined the function on my form... def get_invitee_name(self): invitees = self.cleaned_data.get('approvers') return invitees But when I try to call the function in my template as {{ invitees }} ...nothing shows up. Do I need to define this as a context variable as well? Do I have to do this using Javascript instead or is there a way to do this with pure Django/Python? I'm using a ModelForm if it matters. Thanks in advance for any thoughts. -
How can I prevent django from claiming localhost port 80 via httpd after I've removed my project?
My problem is that my localhost port 80 is taken by an auto-reloading Django proc that I no longer need and I cannot kill the Django proc(s) because they auto-reload upon being killed. I did Django a while ago for an interview assignment so it's not trivial to get back into that and manage it that way. Is there a way simply on macos to prevent this process from coming back? I've tried using launchctl but it's unclear which item would be facilitating the auto-reloading. I have 2 mystery django process that get auto-reloaded whenever I kill it with sudo kill {PID}. i.e. I kill the procs, I check to make sure port 80 is not being used anymore with sudo lsof -i :80, and it shows 2 new procs that have auto-reloaded. I am hoping to do anything at all so that when I run sudo lsof -i :80 I get no results. -
django channels hadling connection
I get trouble with django channels i guess its with hadling connection on client, but maybe isnt. So my code look like this: class ExternalDataConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.active_connections = {} async def connect(self): self.room_group_name = f"external_{self.scope['user'].id}" # Match the group name from the signal await self.channel_layer.group_add(self.room_group_name, self.channel_name) logger.info(f"Connected to group: {self.room_group_name}") await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): try: data = json.loads(text_data["text_data"]) if data: asyncio.ensure_future(await self.start_external_stream(data)) else: asyncio.ensure_future(await self.stop_extenal_stream(data)) # start or stop external stream except Exception as e: logger.error(f"ERROR receiving websocket: {e}") async def start_external_stream(self, data): # do something with data, send payload and get data from stream async def stop_external_stream(self, data): # stop existing steam for data async def send_notification(self, data): # sending notification to user So issue is when i start getting data from external stream its double each time when user reload page. On client im just like get data from django channels websocket like this: if (isWebSocketConnected === 'true') { socket = new WebSocket('ws://0.0.0.0:8000/ws/binance_consumer/'); } else { socket = new WebSocket('ws://0.0.0.0:8000/ws/binance_consumer/'); localStorage.setItem('websocketConnected', 'true'); } const notifications = []; // Handle WebSocket events socket.addEventListener("open", (event) => { console.log("WebSocket connected"); }); socket.addEventListener("message", (event) => { const data … -
Can't reallocate empty Mat with locked layout error in django view
I'm trying to do an image upscaling app using OpenCV and i have an error says that : OpenCV(4.8.1) D:\a\opencv-python\opencv-python\opencv\modules\core\src\matrix_wrap.cpp:1286: error: (-215:Assertion failed) !(m.empty() && fixedType() && fixedSize()) && "Can't reallocate empty Mat with locked layout (probably due to misused 'const' modifier)" in function 'cv::_OutputArray::create' and in the terminal say that : [ WARN:0@3.616] global loadsave.cpp:248 cv::findDecoder imread_('/media/images/wolf_gray.jpg'): can't open/read file: check file path/integrity wolf_gray.jpg is the name of the image that the user uploads it from the form this is the project tree ├───AISystem │ └───__pycache__ ├───img_upsc │ ├───images │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───images │ └───__pycache__ ├───media │ └───images ├───static │ ├───css │ ├───imgs │ │ ├───cards │ │ ├───myfont │ │ └───result │ └───js ├───XOXOXOAPP │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───XOXOXOXOApp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ └───XOXOXOXOXOAPP ├───migrations │ └───__pycache__ ├───templates └───__pycache__ and this is the app files img_upsc app folder view.py def img_upscaler(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) selection = request.POST.get('mod_sel') enter image description here if form.is_valid(): form.save() image_name = str(form.cleaned_data['Image']) if(selection == "EDSR_x4"): sr = dnn_superres.DnnSuperResImpl_create() path = r'img_upsc\EDSR_x4.pb' sr.readModel(path) sr.setModel('edsr', 4) imgloc = f'/media/images/{image_name}' image = cv2.imread(imgloc) upscaled = … -
for loop in django templates not working as expected
I am creating a django app and am iterating through the images list. I've been at it for hours to no avail. I looked everywhere for help and still couldn't fix it. I successfully got the POST request with ajax and when I print it to the console the images sources are there in the list. But, upon iterating it in the django templates, it doesn't show up. It's funny because it does show up when I click the buy button for that request. Also, I am creating a bookmarklet that upon clicking will send the data of the URL of the current page to views.py. I am using that add the images data src into the list. base.html (template) <body> {% csrf_token %} {% load static %} <script src="{% static 'js/onload.js' %}" type="text/javascript"></script> <img width='100px' src="https://i.ibb.co/37ybzSD/neom-V1-NTz-Srn-Xvw-unsplash.jpg"> <img src="https://i.giphy.com/media/tsX3YMWYzDPjAARfeg/giphy.webp"> {% load socialaccount %} <h1>Billionaire Shopping Game</h1> {% if user.is_authenticated %} <p>Welcome, {{ user.username }} !</p> <a href="logout">Logout</a> {% else %} <a href="{% provider_login_url 'google' %}">Login with Google</a> {% endif %} <a href="javascript:(function() {let script = document.createElement('script'); script.src = '{% static '/js/bookmarklet.js' %}'; document.body.appendChild(script);})();">Bookmarklet</a> <a href="javascript: (() => {alert('Hello');})();">Helo alert</a> <img width="100px" src="{% static 'images/heart.png' %}"> <div> <form method="POST" action="/"> <label … -
Having problem with apache2 w/Django ASGI, WSGI & Postgres on Linode Server
Okay so I have built a social media app with django channels asgi w/POSTGRES database. Test on port 80 Type "help" for help. postgres=# CREATE DATABASE xxxxxxx postgres-# \l List of databases Name | Owner ` | Encoding | Collate | Ctype | Access privileges-----------+----------+----------+-------------+-------------+----------------------- postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (3 rows) postgres=# CREATE DATABASE fetishfun; CREATE DATABASE postgres=# GRANT ALL PRIVILEGES ON DATABASE fetishfun TO django postgres-# CREATE DATABASE fetishfun; postgres=# \q (venv) smoke@django-server:~/fetish_fun$ python3 manage.py runserver 0.0.0.0:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 30 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): account, admin, auth, contenttypes, sessions, sites, socialaccount. Run 'python manage.py migrate' to apply them. October 20, 2023 - 17:35:56 Django version 4.2.6, using settings 'socialnetwork.settings' Starting ASGI/Daphne version 4.0.0 development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. I have it successfully running on port 8000 …