Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NextJS can't connect to uwsgi directly
I'm trying to build an application with django on backend-side and nextjs on frontend-side. Backend is ran by uwsgi. uwsgi --http 0.0.0.0:3000 -w project.wsgi --master --harakiri=60 --pidfile=uwsgi.pid When I'm trying to run npm run build I'm getting errors (I use axios but tried fetch too) cause: Error: socket hang up at Socket.socketOnEnd (node:_http_client:524:23) at Socket.emit (node:events:531:35) at endReadableNT (node:internal/streams/readable:1696:12) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { code: 'ECONNRESET' } Looks like backend doesn't work... But when I run just common wget http://my-backend-url/api/v1/same-url-which-produced-errors everything works fine. I've seen this error when I used connection between docker-containers and on one computer as well Last time I managed it by using nginx as a proxy for uwsgi. But now I just want to understand how to fix it and how to make my app without nginx PS The strange thing what I see in the uwsgi-logs is a stack of same requests (my frontend doesn't do this) [pid: 64|app: 0|req: 13/13] 172.18.0.5 () {32 vars in 462 bytes} [Tue Jun 18 22:01:42 2024] GET /api/v1/page/?lang=en-US => generated 1755 bytes in 10 msecs (HTTP/1.1 200) 7 headers in 206 bytes (1 switches on core 0) Ten and more times -
Django LDAP authentication without store login informations
I´m novice and I have problem with my django project. I need active directory autentification but I don´t want to store my login informations in database. That´s why I try to use my own ldap backend. When I run my python test file I see all my AD users. Here is code: import ldap3 import sys LDAP_SERVER = "ldap://aaaaa:389" # Adresa vašeho LDAP serveru LDAP_SEARCH_BASE = "dc=pm,dc=cz" # Širší základna pro vyhledávání LDAP_USERNAME = "xxxxx" # Uživatel pro připojení k LDAP (změňte na testovací účet) LDAP_PASSWORD = "yyyyy" # Heslo pro připojení k LDAP (změňte na testovací účet) def main(): \# Vytvoření LDAP server objektu server = ldap3.Server(LDAP_SERVER) \# Vytvoření připojení s daným uživatelským jménem a heslem conn = ldap3.Connection(server, user=LDAP_USERNAME, password=LDAP_PASSWORD) # Pokus o připojení if not conn.bind(): print(f"Failed to connect to the LDAP server. Error: {conn.last_error}") sys.exit(1) # Provedení vyhledávání search_filter = '(&(objectClass=user)(objectCategory=person))' conn.search(LDAP_SEARCH_BASE, search_filter, attributes=['sAMAccountName', 'givenName', 'sn', 'mail']) entries = conn.entries if entries: print(f"Found {len(entries)} entries:") for entry in entries: print(entry) else: print("No entries found") # Odpojení od serveru conn.unbind() if __name__ == "__main__": main() But when I try my django site it still say: Invalid name or password and without error in console. Here is part … -
custom domain mapping and authentication issues
I’m currently working on an application where I’m using Django, GCP MySQL (database). I deployed the application using Google cloud run and I can access the website through its url. Where I’m an facing issue is when linking my registered custom domain with Django, I’m able to access the website when I go to my custom domain url but I’m not able to login through the same url. It gets me redirected again to the login page, instead of going to the homepage, and it also doesn’t give me credentials error when I enter incorrect password/email. Note it works properly when I access it through cloud run service url/ localhost. I really wish I could post some error logs here, but there’s none. I checked the GCP logging service but there’s no error regarding this. I can explain a bit though. After I enter my credentials (url - https://custom-domain.org/login), it shows the login page which is the same url. When I check the logs there’s a successful 302 get request for the home page i.e. https://custom-domain.org, but then there another log having the login request url - https://custom-domain.org/login. I have mapped the cloud run domain url https://iconnect-webapp-dxxqb7rbaa-uk.a.run.app/ to mu custom … -
Why is my Django app running out of memory after switching to Gunicorn?
I got the following error when trying to run a ML/AI app in Django/Docker. The app allows a user to upload audio files which are then transcribed. I started getting the following error after switching to Gunicorn. I understand it is due to memory allocation limitations, but I am not sure how to fix it. The error is inconsistent and only happens with some files and not with others and it is not always the same error. Sometimes I only get a internal server error. The error also happens with longer audio files even if a shorter audio file is larger(so a 10MB, 20 sec audio file may be successful but a 2MB, 3 min file is never successful and always returns a similar error): [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 | … -
Using Django session authentication with access token + refresh token?
I am currently developing a project using django rest framework. I want to integrate social account log in like Google etc. This is working but the oauth2 response returns an access token, refresh token and id token which is a JWT. An example of the reponse is below. But for users who dont use social log in, they receive a session id cookie. { "access_token": "ya29.a0AXooCgtlrshHEmZpGgjtAf--tHWg3R0XVHRvu8loe6lz6cAEAsI3PltGks71uBC5HJDb35sMkFcLKzOKW2en4Vr39ywt7YP9kMotXMxaTcrJyaZTC3xPuv9LlSCzsqrU2wgQTChmA7iyxmQH5XTT2BibhoyUFdxGSG0caCgYKATMSARISFQHGX2MiJk5x1uikM0e2q-nhXEBMnQ", "expires_in": 3599, "refresh_token": "1//0gxxUoZyRFO9ECgYIARAAGBASNwF-L9IrGHliubMCOWomlmTTzSh4aKwmS1GeVoNmBB6-6VZ-a2MQAzoSzS3B-e_KL8NUyCh3", "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid", "token_type": "Bearer", "id_token": "jwt token" } So should I just use Django's default session auth together with the access_token and refresh token stored in cookies? Seems a bit complicated to keep track of all of these in cookie. I tried searching around but cant seem to find much, any help would be greatly appreciated. -
How to communicate a postgres db and Django container inside ECS?
I need some guidance with this pipeline to deploy a test to ECS, i know that a postgres db in a container is not the best solutions compared to RDS and others but i would like at least to know if it is possible hehe. Im stuck with this for days, it just get stuck in part of running wait-for-it.sh file and does not connect to db, i checked in AWS cloudwatch and the db is getting ready to accept connections, but Django never connects to it. Im using a default VPC attached to the ECS cluster and have inside it a security group with inbound rules to allow traffic in port 8000 for ay IP and other for 5432 port that allows traffic to any IP too, what is wrong? name: CD Pipeline on: push: branches: - main jobs: deploy-ecs: name: Deploy to ECS runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ secrets.AWS_REGION }} - name: Log in to Amazon ECR uses: aws-actions/amazon-ecr-login@v1 - name: Check if backend Docker image exists id: … -
Can't solve this error: UNIQUE constraint failed: auth_user.username
I have searched up and down for the solution but can't seem to find one. I have this form for registering users on an eLearning platform, the login functionality works fine but when signing up it returns this error message. Here is my forms.py file: from django import forms from .models import Contact as con, Subscription as subs from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # registration form class register(UserCreationForm): # create User form FirstName = forms.CharField(max_length=30, required=True) LastName = forms.CharField(max_length=30, required=True) UserName = forms.CharField(max_length=30, required=True) Email = forms.CharField(max_length=255, required=True) class Meta: model = User fields = [ "FirstName", "LastName", "UserName", "Email", "password1", "password2", ] and this is my views.py file: def logout_user(req): # log the user out logout(req) return redirect("Home") def dash(req): if req.method == "POST": # if the user is signing up if "signup" in req.POST: form = register(req.POST) print(form) if form.is_valid(): # save form.save() # get the username and password username = form.cleaned_data.get("UserName") password = form.cleaned_data.get("password1") # authenticate and log the user in user = authenticate(username=username, password=password) login(req, user) # drop a success message messages.success(req, "You have successfully signed up!") # render back the page return render(req, "dashboard.html") else: fname = req.POST["FirstName"] lname = req.POST["FirstName"] email … -
Server Side Handling HTTP Request Post Data in Python
For client side, I use Swift to make Post HTTP request as follows: static func postNonceToServer(paymentMethodNonce: BTPayPalAccountNonce, deviceData: String) { let paymentURL = URL(string: "http://server.openxverse.com/shop/transac")! var request = URLRequest(url: paymentURL) request.httpBody = "payment_method_nonce=(paymentMethodNonce)&device_data=(deviceData)".data(using: .utf8) request.httpMethod = "POST" URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in if let data = data { print("success data from postNonceToServer", data) } else if let error = error { print("error from postNonceToServer", error) } else { print("what happen from postNonceToServer") } }.resume() } On the server side, I would like to use Python and Django for http POST requests. def post(self, request): result = gateway.transaction.sale({ "amount": "10.00", "payment_method_nonce": nonce_from_the_client, "device_data": device_data_from_the_client, "options": { "submit_for_settlement": True } }) if result.is_success: return Response(true, status = status.HTTP_201_CREATED) else: return Response(false, status = status.HTTP_400_BAD_REQUEST) but the question is, on the server side, how do I access the POST request body data "payment_method_nonce" and "device_data" in "def post"? Note that I could not use Json to send the POST request since BTPayPalAccountNonce is not json encryptable. Great appreciate your help! -
Why NGINX doesn't work with Django project?
I have a Django project that works using setup Django web-server. I want to use nginx and uWSGI. I created a directory in root Django folder called nginx/nginx.conf and nginx/default.conf to set nginx. Ir successfully works at http://localhost:8080 and shows nginx start page (site also starts with uwsgi --http :8000 --module brand_site.wsgi). But when I try http://localhost:8080/blog/corgifume-posts/ it shows 404 Not Found. What's the problem? Why my site doesn't work with nginx? nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; include /opt/homebrew/etc/nginx/uwsgi_params; # where my uwsgi_param stores in local machine server_tokens off; include /opt/homebrew/etc/nginx/default.conf; } default.conf server { listen 8080; # what port to listen server_name localhost; location / { proxy_pass http://127.0.0.1:8000; # where to address requests proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } uwsgi.ini [uwsgi] wsgi-file = config/wsgi.py strict = true socket = :8000 protocol = http master = true no-orphans = true die-on-term = true lazy-apps = true processes = 4 threads = 8 enable-threads = true max-requests = 500 reload-on-rss = 1024 worker-reload-mercy = 60 harakiri = 60 harakiri-verbose = true vacuum = true post-buffering = 1048576 buffer-size = 65535 The path to my … -
why the css not linked to the index.html
I'm working on making "is it newyear page" and the page should answer with yes or no, this is not the problem but the problem here is with the link i wrote this link inside of the <head' which is <link href= "{% static 'newyear/styles.css'%} rel="stylesheet" and i run the server but nothing from my style applied to the page so I'm trying to figureout what is the problem some details: the app name is newyear i have a folder inside of it called static/newyear and the styles.css file inside of the newyear folder i did not try anything to solve it because there is only this way to link i just deleted the link and tried it many times but still not working this image of the index.html which is have the link this is image of the styles.css file -
How to profile Celery / Django in docker?
I have a Django / Celery application services: django: build: ./project # path to Dockerfile command: sh -c " sleep 3 && gunicorn --bind 0.0.0.0:8000 core_app.wsgi" volumes: - ./project:/project - ./project/static:/project/static - ./project/media:/project/media - ./project/logs:/project/logs expose: - 8000 env_file: - ./.env depends_on: - db ... celery: build: ./project command: celery -A core_app worker --loglevel=info --concurrency=16 volumes: - ./project:/usr/src/app - ./project/media:/project/media - ./project/logs:/project/logs env_file: - .env environment: # environment variables declared in the environment section override env_file - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - django - redis How to use profiler for my Celery tasks? I read Celery tasks profiling Looks like I should use https://github.com/ask/celerymon Could you please explain how to add profiler to my infrastructure? I guess it should be somewhere in docker-compose file -
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'> …