Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List of playlists not displaying Django music app
i'm making a music streaming website and i'm trying to display the user's list of playlists in the , but i always get that the user has no playlists(but there are playlists in database for the user). What is the problem? maybe the playlist view is not correct? html: <div id="divId"> {% if myPlaylists %} <p style="margin: 5px; font-size: 0.75rem; font-weight: 700; color: rgb(138, 138, 138); text-align: left;">Add This Song To Your Playlist</p> {% for playlist in myPlaylists %} <a class="left-panel-btn" id="D_{{playlist.playlist_id}}" onclick="sendPostRequestPlaylistSong(this)">{{playlistInfo.playlist_name}}</a><br> {% endfor %} {% else %} <p style="margin: 5px; font-size: 0.8rem; font-weight: 700; color: rgb(138, 138, 138); text-align: left;">You don't have any Playlist.</p> <a class="create-p" onclick="$('#divId').css({display: 'none'}); document.getElementById('modal-wrapper-playlist').style.display='block'"><i class="fas fa-plus"></i> Create Playlist</a> {% endif %} </div> models.py: class Song(models.Model): song_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) artist = models.CharField(max_length=50) album = models.CharField(max_length=50, blank=True) genre = models.CharField(max_length=20, blank=True, default='Album') song = models.FileField(upload_to="songs/", validators=[FileExtensionValidator(allowed_extensions=['mp3', 'wav'])], default="name") image = models.ImageField(upload_to="songimage/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], default="https://placehold.co/300x300/png") data = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField() def __str__(self): return self.name class Meta: ordering = ['name'] class Playlist(models.Model): playlist_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) playlist_name = models.CharField(max_length=50, default="name") image = models.ImageField(upload_to="playlist_images/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], default="media/images/music-placeholder.png") plays = models.IntegerField(default=0) songs = models.ManyToManyField(Song, related_name='playlist') slug = models.SlugField() def … -
AWS AppRunner with Python 3.11.x failing health check when same config with Python 3.8.16 passes
I've been trying to deploy a django web app on AWS AppRunner. I followed an AWS tutorial here which works to deploy an app running on python 3.8.16. I tried to follow the same procedure but use python 3.11.9 which is supported by AppRunner, but I ran into a connectivity error where the deploy fails health check: The AppRunner Event Log would output: Health check failed on protocol TCP [Port: '8000']. Check your configured port number. For more information, see the application logs. Deployment with ID : xxxxxxxxxx failed. Failure reason : Health check failed. The Application Logs would output: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at xxxxxxxxx>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /simple/asgiref/ I made sure the change references to pip and python to pip3 and python3 respectively in startup.sh, and changed 'python3' to 'python311' and runtime version to '3.11.9' in apprunner.yaml. I tried changing the TCP port (tried 8000 and 8080), and tried changing the health check protocol to HTTP and the port to 80 to no avail. I also tried changing security group arrangement extensively (including allowing connection from any ip address on the respective … -
HTMX cannot find element on site
I'm trying to build a webapp with django and htmx. One of the functionalities with htmx is that I want to dynamically insert rows into a table. For that I have... a base.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap 5--> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/bootstrap.min.js' %}" defer></script> <!-- HTMX --> <script src="{% static 'js/htmx.min.js' %}" defer></script> <!-- Favicon --> <link rel="shortcut icon" type="image/svg" href="{% static 'favicon.svg' %}"/> <title>Document</title> </head> <body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'> {% include 'navbar.html' %} <div class="container-fluid"> {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> <strong>Holy guacamole! {{ message }}</strong> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} {% block content %} {% endblock %} </div> </body> </html> an "add-periods.html" file: {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} <div class="container-fluid shadow p-4 mb-5 bg-body rounded"> <h3 class="pt-5 text-center">Zeiträume für die Abrechnung erfassen</h3> <h5 class="text-secondary text-center">{{ patient.first_name }} {{ patient.last_name }}, geb. {{ patient.birthday|date:'d.m.Y' }}</h5> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="col text-center"> <h6 class="text-secondary"> Ein paar schnelle Tipps:</h6> <ul class="text-secondary … -
How to fix the "Required field" error when submitting a form with images to the Django Rest Framework
I created a serializer to create a description and a photo: class ImageFileSerializer(serializers.ModelSerializer): class Meta: model = ImageFile fields = ["image"] class DescriptionFileSerializer(serializers.ModelSerializer): image_file = ImageFileSerializer(many=True) file_filename = serializers.CharField() user_id = serializers.ReadOnlyField(source="user.id") class Meta: model = DescriptionFile fields = ["pk", 'file_filename', 'user_id', 'title', 'description', 'line_video', 'tags', 'image_file', "time_create"] read_only_fields = ('time_create',) by sending a request to this views: class DescriptionFileView(ModelViewSet): queryset = DescriptionFile.objects.all().annotate( file_filename=F("file__filename") ).select_related("user", 'file').prefetch_related("tags", "image_file") serializer_class = DescriptionFileSerializer # permission_classes = [IsAuthorOrStaff] filter_backends = [SearchFilter] search_fields = ["time_create", "user__id", "tags__name"] parser_classes = (MultiPartParser, JSONParser) def perform_create(self, serializer): serializer.save(user=self.request.user) I get an error: { "image_file": [ "Required field." ] } I use this html form to send a request: <form action="http://localhost:8000/api/description/file/" method="post" enctype="multipart/form-data"> <label for="title">Title:</label> <input type="text" id="title" name="title"><br><br> <label for="description">Description:</label> <textarea id="description" name="description"></textarea><br><br> <label for="line_video">Line Video:</label> <input type="text" id="line_video" name="line_video"><br><br> <label for="tags">Tags:</label> <input type="number" id="tags" name="tags"><br><br> <label for="file">File:</label> <input type="text" id="file" name="file_filename"><br><br> <label for="image_file">Image:</label> <input type="file" id="image_file" name="image_file.image"><br><br> <input type="submit" value="Submit"> </form> how can I fix the error? python==3.11.9 django==4.2.11 drf==3.15.1 I searched for a question, found +- similar questions, but they did not help -
Django / Docker app out of memory after switching to Gunicorn
I get the following error when trying to run a ML/AI app in Django/Docker. I started getting the error after switching to Gunicorn. I understand it is due to memory allocation limitations but I am not sure how to fix it. [2024-06-18 08:56:09 -0500] [19] [INFO] Worker exiting (pid: 19) web-1 | [2024-06-18 13:56:10 +0000] [1] [ERROR] Worker (pid:19) was sent SIGKILL! Perhaps out of memory? web-1 | [2024-06-18 13:56:10 +0000] [34] [INFO] Booting worker with pid: 34 web-1 | /usr/local/lib/python3.11/site-packages/whisper/__init__.py:63: UserWarning: /root/.cache/whisper/tiny.pt exists, but the SHA256 checksum does not match; re-downloading the file web-1 | warnings.warn( 78%|█████████████████████████████ | 56.6M/72.1M [00:24<00:05, 2.74MiB/s][2024-06-18 13:57:18 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:34) 79%|█████████████████████████████ | 56.7M/72.1M [00:24<00:06, 2.42MiB/s] web-1 | [2024-06-18 08:57:18 -0500] [34] [INFO] Worker exiting (pid: 34) web-1 | [2024-06-18 13:57:19 +0000] [1] [ERROR] Worker (pid:34) exited with code 1 web-1 | [2024-06-18 13:57:19 +0000] [1] [ERROR] Worker (pid:34) exited with code 1. web-1 | [2024-06-18 13:57:19 +0000] [45] [INFO] Booting worker with pid: 45 web-1 | /usr/local/lib/python3.11/site-packages/whisper/__init__.py:63: UserWarning: /root/.cache/whisper/tiny.pt exists, but the SHA256 checksum does not match; re-downloading the file web-1 | warnings.warn( 72%|██████████████████████████▊ | 52.2M/72.1M [00:24<00:10, 2.03MiB/s][2024-06-18 14:02:49 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:45) 73%|██████████████████████████▉ | 52.4M/72.1M [00:24<00:09, 2.22MiB/s] web-1 … -
Unique submit btn for each user - django
I have a Like button for my posts which users can like the posts or not, which means if a user clicked on the button for the first time the post will be liked by the user and for the second time it will be unliked by the user. just like Facebook or twitter and etc. I tried a lot to do this but my problem is " when user click on the button it will add one like on the counter and if a user likes again it will count 2 likes for the post by a user! Anyway, how we can make the likes unique? Each user should be able to like any post just once and if they clicked again it means they unliked a post. if request.POST.get("single_tweet_like_submit_btn"): try: # Debug: Check the request and user print(f"Request by user: {current_basic_user_profile.user.username} for tweet ID: {current_tweet.id}") # Check if the user has already liked the tweet tweet_like = TweetLike.objects.filter(tweet=current_tweet, liker=current_basic_user_profile) if tweet_like: # Debug: User has already liked the tweet, so we'll unlike it print(f"User {current_basic_user_profile.user.username} has already liked tweet {current_tweet.id}, unliking it.") # If the user has already liked the tweet, unlike it tweet_like.delete() # Decrement the like … -
Issue with Toggling between Themes
I'm encountering an issue with a custom Theme Installation in my Django project using v. 4.2.13 and Python v. 3.9.7. In the default Admin side, there is a Moon icon for toggling the Themes (i.e. b/w Light and Dark and Auto). I want to add a Grey theme as my default with a new icon. So there are total 4 icons for themes now - Grey, Light , Dark & Auto. For implementing this, I added a new icon for the Grey theme and the icon is now not visible in the Admin panel (only the default 3 are shown) and the toggling between themes is not working. Below are the screenshots of the code for installing themes with their respective icons. Please also note my teammate has been working on Django 5.0 for making his previous project commits in Github. We wanted to test what can happen to the same functionality if team members work on different versions since we're assuming Git essentially stores all files as basic text files with version control. I am not sure if this has anything to do with my problem. Kindly help. 1.Screenshot 1 - js file for toggle and add the icon … -
Django messages showing up from models.py
Now I am trying to build messaging functionality into my webapp, where businesses can message buyers and users can message sellers. The messaging functionality works fine, but the problem is, debug django messages show up such as Message from john to steve in Lululemon, from models.py str method. Now I don't know how to get rid of these messages for this view or why this is happening. My models.py: class Message(models.Model): sender = models.ForeignKey(CustomUser, related_name='sent_messages', on_delete=models.CASCADE) recipient = models.ForeignKey(CustomUser, related_name='received_messages', on_delete=models.CASCADE) business = models.ForeignKey(Business, related_name='messages', on_delete=models.CASCADE, null=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return f'Message from {self.sender} to {self.recipient} in {self.business}' @property def sender_is_business(self): return self.sender.business.exists() @property def recipient_is_business(self): return self.recipient.business.exists() My views.py: @login_required def message_seller(request, business_slug): business = get_object_or_404(Business, business_slug=business_slug) if request.method == 'POST': content = request.POST.get('content') if content: Message.objects.create( sender=request.user, recipient=business.seller, business=business, content=content ) return redirect('message_seller', business_slug=business.business_slug) # Mark messages as read for the current user and business Message.objects.filter(recipient=request.user, business=business).update(is_read=True) messages = Message.objects.filter( Q(sender=request.user, recipient=business.seller) | Q(sender=business.seller, recipient=request.user) ).filter(business=business).order_by('timestamp') individual_business_message_counter = Message.objects.filter(recipient=request.user, business=business, is_read=False).count() context = { 'business': business, 'messages': messages, 'individual_business_message_counter': individual_business_message_counter, } return render(request, 'business/message.html', context) @login_required def message_buyer(request, username): user = get_object_or_404(CustomUser, username=username) business = Business.objects.filter(seller=request.user).first() if not business: return … -
django template doesn't apply css
i want to use text-align = justify and reduce text width on a django template file but it doesn't work. static files and direction are working without problem but i can't do something to only this django element and i have no idea how to fix this. it's my css script : #name1{ text-align: justify; width: 20%; } #name2{ position: relative; text-decoration: none; color: black; font-family: lalezar; } and this my HTML script : <html> <header> <body> {% for item in post %} <div id="post1"> <a href="{% url 'page_detail' item.pk %}" id="name2"><h2 id="name1">{{item.title}}</h2></a> <h3>{{item.author}}</h3> </div> {% endfor %} </body> </header> </html i searched google but i didn't found anything. -
How to do daily and Hourly task in django
I use Django 4.2.11 and I try to run a task hourly (or multiple task). I found django-background-tasks and Django-Q but it all seem that they are old. I also seen that Celery can do that but it's not integrated in Django. is Celery a good way ? -
Javascript function to play songs not working Django app
i'm making a music streaming website and i have this js function that plays the songs on a single player onclick. the songs are playing correctly but when i click on them the player thakes always the song name, the song artist and the song image of the first song, also if i click on the others. how can i fix that? This is the js function: function playSong(element){ var songUrl = element.getAttribute('data-song-url'); var audioPlayer = document.getElementById('audioPlayer'); var audioSource = document.getElementById('audioSource'); audioSource.src = songUrl; audioPlayer.load(); audioPlayer.play(); var songId = element.id; var newImage = document.getElementById("A_" + songId).src; var newSongName = document.getElementById("B_" + songId).textContent; var newArtistName = document.getElementById("C_" + songId).textContent; console.log(newSongName) //always displaying the things of the first song console.log(newImage) console.log(newArtistName) document.getElementById("audio-img").src = newImage; document.getElementById("audio-song").textContent = newSongName; document.getElementById("audio-artist").textContent = newArtistName; } and this is the HTML code: {% for i in songs %} <div class="carousel-cell"> <section class="main_song"> <div class="song-card"> <div class="containera"> <img src="{{i.image}}" id="A_{{i.id}}" alt="song cover"> <div class="overlaya"></div> <div> <a class="play-btn" data-song-url="{{i.song.url}}" id="{{i.id}}" onclick="playSong(this)"><i class="fas fa-play-circle fa-2x"></i></a> {% if user.is_authenticated %} <div class="add-playlist-btn"> <a id="W_{{i.song_id}}" title="Add to Playlist" onclick="showDiv(this)"><i class="fas fa-ellipsis-h"></i></a> </div> {% endif %} </div> </div> </div> <div> <p class="songName" id="B_{{i.id}}">{{i.name}}</p> <p class="artistName" id="C_{{i.id}}">{{i.artist}}</p> </div> </section> </div> {% endfor %} -
How to test Djang PasswordChangeForm
I am trying to write a test for my changing password view, which users the PasswordChangeForm. This is the test: def test_profile_change_password(self): self.client.force_login(self.user) self.user.set_password(self.password) new_password = random_password() payload = { "old_password": self.password, "new_password1": new_password, "new_password2": new_password, } form = PasswordChangeForm(user=self.user, data=payload) self.assertTrue(form.is_valid()) response = self.client.get( reverse_lazy("researcher_ui:change_password"), ) self.assertEqual(response.template_name, ["researcher_UI/change_password.html"]) response = self.client.post( reverse_lazy("researcher_ui:change_password"), payload ) print(response.context['form'].error_messages) The self.assertTrue(form.is_valid()) test works but when I then try and process the same data through the view I am getting the following errors: {'password_mismatch': 'The two password fields didn’t match.', 'password_incorrect': 'Your old password was entered incorrectly. Please enter it again.'} The form.is_valid() shouldn't have return True if this were the case, so what am I doing wrong? -
Django: Request object attributs options doesn't show up
I have started first time using django. When creating a function view, I wanted to see what are the atributes of the object request (method, etc) and I excpected that VSC will show all options for the request.option. But the request object doesn't show anything. I wonder if it is something of the configuration of extention for django to help with autocomplete or showing options, or it is that that is a normal thing. def index(request): print( request.) return HttpResponse("Hello, World!") I take this code as an exemple of what I would like to see, and i expected that vsc will show a list of options to see the properties of request object: def xyz(request): item1 = request.GET['item1'] user = request.user Per exemple, if I do request.me the autocomplete do something like that about the class request: def index(request): request.(self, *args, **kwargs): return super().(*args, **kwargs) Of course I don't want this, but I would like to see the options and the autocomplete of the request object. For exemple, to check if the request is a GET or POST methode. I would like to know if that is about the configuration of VSC when working with django, or is a normal … -
How to fetch different data into different sections in html ? (DJANGO)
I have a page on which there are different bootstrap accordians, i have different models stored in the database, Now i want to fetch them in a proper order ? class CaseStudy_list(models.Model): CaseStudy_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) def __str__(self): return self.title class CaseStudy_parts(models.Model): #accordians case_study = models.ForeignKey(CaseStudy_list, on_delete=models.CASCADE) CaseStudy_part_id = models.AutoField(primary_key=True) CaseStudy_order = models.IntegerField(default="") CaseStudy_title_accordian = models.CharField(max_length=255) def __str__(self): return self.CaseStudy_title_accordian class CaseStudy_content(models.Model): #column 1 - text area case_study = models.ForeignKey(CaseStudy_list, on_delete=models.CASCADE) content_title = models.CharField(max_length=255, default="") content_text = models.TextField(blank=True) content_link = models.TextField(blank=True) def __str__(self): return self.content_title class CaseStudy_Media(models.Model): #column 2 - Media Area case_study = models.ForeignKey(CaseStudy_list, on_delete=models.CASCADE) content_img = models.ImageField(upload_to='casestudy/images', default="") class CaseStudy_buttons(models.Model): content = models.ForeignKey(CaseStudy_content, on_delete=models.CASCADE) button_id = models.CharField(max_length=255) button_label = models.CharField(max_length=255) <div class="page-layout"> <div class="accordion" id="accordionPanelsStayOpenExample"> <div class="accordion-item"> <h6 class="accordion-header"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne"> {{content.section_title}} </button> </h6> <div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show"> <div class="accordion-body"> <div class="container-area"> <div class="col-content"> <div class='introduction-content'> <h3>CASESTUDY ID - {{casestudy_obj.id}} </h3><br> <h3>TITLE - {{ casestudy_obj.title }} </h3> <br> <h3>OBJECTIVE - {{content.content_text}}</h3> </div> </div> <div class="col-data"> <img src="{{content.content_img.url}}"> </div> </div> </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo"> DATA COLLECTION </button> </h2> <div id="panelsStayOpen-collapseTwo" class="accordion-collapse collapse"> <div class="accordion-body"> <div class="container-area"> <div class="col-content"> <div class='introduction-content'> … -
Django sorting by Date, Name
I am new in Django, and I want to sort my querys by date or name. I did it but I additonally want to do an option to change it on website. I coudln't find an answer anywhere how to do it. Am I going wrong way? I tried do do it like that: {% block content %} <h1 class="tytul">Lokalizacja plików</h1> <div class="naglowek"> <div class="card card-body"> <p>Wyszukaj plik</p> <form method="get">{{myFilter.form}} <button class="button" type="submit"> Wyszukaj </button> </form> <div class="sortowanie">Wybierz po czym sortować: <select class="sort"> <option>Nazwa</option> <option>Data</option> </select> </div> </div> </div> HTML {% for plik in obj %} <div class="row"> <div class="com"> {{plik.nazwa}} </div> <div class="com"> {{plik.data}} </div> <div class="com"> {{plik.lokalizacja}} </div> <div class="przy"> <a href="{% url 'download' plik.lokalizacja %} " class="button">pobierz</a> </div> </div> {% endfor %} </div> {% endblock %} I am trying to do and option to change sorting by date and name by user -
Django App with Automation File Upload from user local system
I want to create a website based on python and django in backend and bootstrap, css, jquery and javascript in the frontend, the functionality will be like user will provide a "Source_Path" from his local system irrespective of the os used by the user, it will upload all the files from that folder in our django project! Is this possible? Can we make this automation I have tried using os it is working in my local, but in production it is not working! I have deployed using apache2 web server. Any suggestion can help! -
Raise Validation error in the forms.py when the header/row is empty or not correct wording
I have been trying to solve this issue for a while and am stumped, this issue is a bit unique in a sense that the csv file that I am checking the header for is from a file upload in the forms.py. What I mean is that the csv file being checked does not exist in any directory so you can't just open a specific file, just from my research of other solutions, they all seem to be about an existing file in a directory rather than a file upload. So, the header must = "IP Address", and the form will submit without an issue, when the file header is equal to " " or != "IP Address", when the form gets submitted the Django debug window comes up. I am struggling with inputting a validation error or implementing a redirect. If you have any useful links, documentation, or would like to solve, please feel free I would appreciate it a lot. import csv import io import pandas as pd from typing import Any from django import forms from django.core.exceptions import ValidationError from django.core.validators import FileExtensionValidator from api.utils.network_utils import NetworkUtil from .models import BlockedList forms.py class CSVForm(forms.Form): csv_file = forms.FileField(required=True, … -
NoReverseMatch error when trying to make a Django Python website
i don't really know what im doing so i'll provide as much context as i can lol. Have to make a "business solution" for school and wanted to do a website built with django as i kind of know a bit about python. Made a design using figma, used some ai tool to convert that into html/css code. Moved that all over to python and initially the website had some functionality, the index page looked as it should've looked and there were buttons, but as soon as i tried adding functionality to the buttons my site kind of died. After starting the website locally instead of seeing anything i get a NoReverseMatch error. Updated views.py and urls but still can't figure out what the overall issue is, and i presume this issue will be persistent with every other button until i can nail exactly why it's not working. Attached is the error, my directory, views.py code, urls.py code, and html code. images Again i don't really know what im doing so i just asked chatgpt, lead me around in circles and never went anywhere lol -
Django admin panel not loading css/js on digitalocean server
Running into a problem where in my localhost things are working great with this structure: localhost But on digitalocean server I got this structure: server Notice how on the server I got an extra static folder called 'staticfiles'. On my localhost it's working great but at the server level my admin panel can't seem to find the right css/js because it is looking for the files inside the static folder. These are my settings file: `BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]` I am not using a droplet but the app platform option. Any ideas to help me? -
How to connect Django with mongodb Atlas
I'm creating a Django connection with mongodb Atlas, but I get the following error message when using the makemigrations command: django==4.0 Python==3.10.12 djongo==1.3.6 pymongo==4.7.3 #! settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'syscandb', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://<user>:<senha>@clusterak.mp9ylv1.mongodb.net/syscandb?retryWrites=true&w=majority' } } } In MOngo Atlas it guides like this: mongodb+srv://<username>:<password>@clusterak.mp9ylv1.mongodb.net/?retryWrites=true&w=majority&appName=clusterak I tested successfully via python like this: "mongodb+srv://<username>:<password>@clusterak.mp9ylv1.mongodb.net/?retryWrites=true&w=majority&authSource=admin" (venv) rkart@rkart-B-ON:/home/jobs/micakes/syscan$ python3 manage.py makemigrations No changes detected Traceback (most recent call last): File "/home/jobs/micakes/syscan/manage.py", line 24, in main() File "/home/jobs/micakes/syscan/manage.py", line 20, in main execute_from_command_line(sys.argv) File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/core/management/init.py", line 425, in execute_from_command_line utility.execute() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/core/management/init.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 386, in run_from_argv connections.close_all() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/db/utils.py", line 213, in close_all connection.close() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 305, in close self._close() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/djongo/base.py", line 208, in _close if self.connection: File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/pymongo/database.py", line 1342, in bool raise NotImplementedError( NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None -
Firefox can’t establish a connection to the server at ws://127.0.0.1:port
I built a chat app that users will be able to call, sending texts and pictures each other. when i click on call button, I should see my stream and the second user that I am calling to. I just can see my camera and can not see my contact. if another user tries to call me it will happen the same again. How to fix the problem? error on console: **Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/ws/call/username/** `# chat/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope\['url_route'\]\['kwargs'\]\['username'\] self.room_group_name = f'chat\_{self.room_name}' # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): # Handle incoming WebSocket messages text_data_json = json.loads(text_data) message = text_data_json['message'] # Broadcast message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): # Send message to WebSocket message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) ` decorators.py `from functools import wraps from django.shortcuts import redirect from django.urls import reverse from authentication.models import BasicUserProfile def basic_user_login_required(view_func): @wraps(view_func) def _wrapped_view(request, … -
Django FormField that creates several inputs and maps them to model fields
I am using django-modeltranslation to have certain fields of my models in multiple languages. For example, I translate the name field, which leads to several fields in the model and database, like name, name_en, name_gr, etc.. Now I want the user to be able to edit the name and it's translations in a form. And I want the user to be able to select the language they want to edit, so I want to render all fields (i.e. name_en, name_gr) and add some JS to show only one of them and select others. Now I could easily add both fields to the form, add them to a template and add the JS. However I have several forms with these multilingual fields and would prefer to find a generic solution as custom form field. So something like this: class MultilingualForm(ModelForm): name = MultilingualField() class Meta: model = SomeModel fields = ["name"] However I cannot think of a way on how to map a custom form field to several model fields. I this even possible? -
How do I add more left to each iteration of my FOR using Django Language Template + HTML?
I'm having problems making a code in HTML + DLT for printing documents (Delivery Note). What happens is that the customer needs the products to be next to each other. I will ite the products through For, where the first product would have left:8mm and the second would be added 40mm. However, if there are more than 2 products, the third always overlaps the second! I would need that with each iteration of my FOR, more LEFT be added to <span>, starting with 8mm and increasing from 40mm to 40mm. Full code: <div style="font-family:none;"> <style> @import url('https://fonts.googleapis.com/css2?family=Libre+Barcode+39&display=swap'); @page {margin:0;font-family: Arial !important;} html * {font-family: Arial } table{border-collapse: collapse;table-layout: fixed} .padding-td {padding:0.3cm} .check-box {width:0.2cm;height:0.2cm;border:1px solid;margin-right:0.1cm} table td{color:#000;border:1px solid;vertical-align: initial;} .cell_azul{background: #d8e1f2;font-size: 7pt;} .right{text-align: right;} .center{text-align: center;} .cell_cinza{background: #f5f5f5;height:26px;} .cell_branco{background: #fff;} .cert{width:1.42cm;height:1.85cm;border:solid 1px} .contact-text{margin-left:auto;font-size:14px;margin-top:0.1cm} .table-texts{display:flex;flex-direction:row;font-size:13px;height:0.7cm} .size-texts {font-size: 10px } .absolutes {position: absolute;padding: inherit;text-align: left;font-size: 14px;font-weight: bold} </style> {% for delivery_note in delivery_notes %} <div style="min-width: 21cm;min-height: 29.5cm;background: #fff;padding-top: 5mm;padding-left: 15mm;page-break-after: always;position:relative"> <!--DESCRIPCIÓN DE HORMIGON--> {% with 8 as initial_left %} {% for product_note in delivery_note.products_note %} {% if forloop.first %} <span class="absolutes" style="top:54mm;left: {{ initial_left }}mm;width: 10cm; font-size: 14px;font-weight: bold;"> {{ product_note.product.name }} </span> {% else %} {% with initial_left|add:forloop.counter0|add:forloop.counter|add:40 as left_addition … -
how get -> ( path of the photo file for face-picture-comparator module (pypi.org) in django project root in file utils.py )?
in Windows 10 enterprise , vscode 1.88.0 , Django==5.0.3 , face-picture-comparator==0.0.4 , face-recognition==1.3.0 , face_recognition_models==0.3.0. How can I give the face-picture-comparator module the path of the photo stored in the sqlite database and in the static folder in my Django project root in file -> utils.py ? Consider utils.py in django project root folder: from face_picture_comparator import load_img from face_picture_comparator import comparation from face_picture_comparator import plot import os from django.conf import settings from django.contrib.staticfiles import finders from django.templatetags.static import static def get_face_compare_result(image, image_compare): # result = finders.find(image_compare) # print(result) image_compare = load_img.get_image_file(???) image = load_img.get_image_file(???) # message_result = comparation.confront_faces_message(image, image_compare) # message_result = comparation.confront_faces_message(image, image_compare) comparison_result = comparation.confront_faces( image, image_compare) return comparison_result my error : FileNotFoundError: [Errno 2] No such file or directory: '/static/images/user_profile_image_authenticate/barjawandsaman%2540gmail.com/barjawandsamangmail.com-3140735494931184150742764881890058937-imageProfileAuthenticate.PNG' [17/Jun/2024 14:14:07] "POST /home/api/v1/authenticating_manager_login_by_face/ HTTP/1.1" 500 132469 spot : i search many questions in this forum and other forums in google but i did not find my answer because in this module (face-picture-comparator - pypi.org) i can not find path for image file that here is my input in utils.py -> image = load_img.get_image_file(???) and this module in pure python in other python project is working currectly and do not have problems !!! and my problems … -
Django 5.0, Display flash message in form and retain input values
I have an email submission form with 3 input fields: #forms.py class ContactForm(forms.Form): name = forms.CharField( widget=forms.TextInput(attrs={"placeholder": "* Your name"}) ) email = forms.EmailField( widget=forms.TextInput(attrs={"placeholder": "* Your email address"}) ) message = forms.CharField( widget=forms.Textarea(attrs={"placeholder": "* Your message"}) ) When a user submits the form, a flash message appears below the submit button confirming that the message has been sent. #contact.html <section id="form"> <form action="" method="post"> <h3>Send me an email</h3> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Send"> {% if messages %} {% for message in messages %} <div class="text-center alert alert-{{ message.tags }}" > {{ message|safe }} </div> {% endfor %} {% endif %} </form> </section> #views.py class ContactPageView(SuccessMessageMixin, FormView): form_class = ContactForm template_name = "contact.html" success_url = reverse_lazy('contact') # Return back to the page containing the form success_message = "Your message has been sent. Thankyou." def form_valid(self, form): email = form.cleaned_data.get("email") name = form.cleaned_data.get("name") message = form.cleaned_data.get("message") # Displays in console full_message = f""" Email received from <{name}> at <{email}>, ________________________ {message} """ send_mail( subject="Email from client using website form", message=full_message, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[settings.NOTIFY_EMAIL], ) return super().form_valid(form) The form works fine except that I would like the input values retained after the form has been submitted and with the …