Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add song to Playlist not working Django music App
I'm making a music streaming website (it's my first project on Django). I'm making the view to add a song to a specific playlist, but it is not working (I always get the error "failed to add song to playlist"), and the songs are not added to playlists. How can I fix it? HTML: {% if my_playlists %} <p style="">Add This Song To Your Playlist</p> {% for playlist in my_playlists %} <a class="left-panel-btn" id="D_{{playlist.playlist_id}}" onclick="sendPostRequestPlaylistSong(this)">{{playlist.playlist_name}}</a><br> {% endfor %} {% else %} <p style="">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 %} javascript function: function sendPostRequestPlaylistSong(el) { // alert("Song ID: "+song_id_for_playlist+" | Playlist ID: "+el.id); var data = song_id_for_playlist + "|" + el.id; $.ajax({ "url": "{% url 'music:addSongToPlaylist' %}", "type": "POST", "data": { 'data': data, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function(response) { alert("Song added to your playlist"); location.reload();}, error: function(xhr, status, error) { alert("Failed to add song to playlist.");} }); var div = $("#divId"); div.css({ transition: "0.3s", display: "none" }); } views.py: def addSongToPlaylist(request): user = request.user if request.method == "POST" and user.is_authenticated: data = request.POST['data'] if data: song_id, playlist_id = data.split("|") song_id = song_id[0][2:] playlist_id = playlist_id[1][2:] currPlaylist = Playlist.objects.filter(playlist_id=playlist_id, user=request.user).first() … -
Django+Heroku testing: how to connect to a test database? ('permission denied to create database')
I have been doing my first deployment with django (ever), and I am using Heroku CLI. I get this message when trying to run tests: "Got an error creating the test database: permission denied to create database" I tried first just by running tests. Then I tried to specify the current database as a test option (giving same parameters). I also tried to specify Sqlite as a test database. I am expecting to have a temporal database for testing, or to use the current database for it. I have found an option that creates a custom connection to a postgress database made for only testing purposes. It seems too complicated to be a common problem. I also saw something in heroku pages called dynos database (a temporal one for testing in Ruby), but could not find it in the add ons on the page, nor when trying to do it from the command line (it says its only for command line deployment). Implementing something like what pasted bellow would be ideal as it makes a database temporaly only for testing (found in Ruby section): https://devcenter.heroku.com/articles/heroku-ci-parallel-test-runs { "addons": [ "heroku-postgresql:in-dyno", "heroku-redis:in-dyno" ] } There is an option in NOD.js that looks … -
Complex Django query related to Prefetch, Subquery and OuterRef
I have this queryset below. queryset = Contract.objects.select_related( "company", "user", "user__profile", "user__profile__address", "user__profile__address__living_country", "compensation__currency", "job", "benefit", "payment_details", "working_country", "work_permit", ).prefetch_related( Prefetch( "partner_fee__partner__partner_countries", queryset=CountryPartner.objects.annotate(contract_id=OuterRef("id")).all() ) ) I have to annotate that contract_id to filter that CountryPartner. But it is not possible to use OuterRef there. It always needs Subquery of django.models. Ideally, I want to do this sql query in Django ORM: select cc.id, cc.email, cc.residency_type, dc.country_id from core_contract cc inner join public.core_partnerfee cp on cc.id = cp.contract_id inner join public.core_partnerprofile c on cp.partner_id = c.id inner join public.dicts_countrypartner dc on c.id = dc.partner_profile_id where dc.country_id=cc.working_country_id and dc.residency_type=cc.residency_type and dc.partner_profile_id=c.id order by cc.id; If I use Subquery inside CountryPartner filter it is going to take CountryPartnerId, not Contract ID. See below pls. Prefetch( "partner_fee__partner__partner_countries", queryset=CountryPartner.objects.annotate(contract_id=SubQuery(Contract.objects.filter(id=OuterRef("id")))) ) So, how to be? Django ORM is not able to do this? -
Django reatApi Request user is Anonymous when using jwt cookies
I'm building a new django restApi app within my users app I'm using jwt authentication currently I'm able to register, login , store cookies and send get request after logging in with a valid credentials. My issue is when I'm getting an authinticated get request I'm not able to see request's user it shown as AnonymousUser. I'm attachinf my login post request and an endpoint restApi get request code. from django.shortcuts import render from rest_framework.exceptions import AuthenticationFailed # Create your views here. from rest_framework.views import APIView from .models import User from .serializers import UserSerializer from rest_framework.response import Response import jwt,datetime class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found') if not user.check_password(password): raise AuthenticationFailed('Incorrect password') payload={'id':user.id,'exp':datetime.datetime.utcnow()+datetime.timedelta(minutes=60), 'iat':datetime.datetime.utcnow()} token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt',value=token,httponly=True) response.data={'jwt':token} return response class UserView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if token is None: raise AuthenticationFailed('Unauthenticatedddd') try: payload=jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) class UsserLogoutView(APIView): def post(self, request): response = Response() response.delete_cookie('jwt') response.data = {'message': 'You have been logged out'} return … -
Can't get route to redirect to login page if user isn't authenticated in React/Django app
I’m using React for my frontend and Django for the backend, both are new to me and I've been spending a ton of time on this issue without solving it, so I'm really hoping someone might know the answer. When I visit my site at http://localhost:4000/ without being logged in, I see a black screen with the text "Loading…” (refer to protected_route code below), instead of being redirected to the login page. This happens when I navigate to any protected routes while not logged in. Currently my only routes that are not protected are the login and register pages, which if I manually go to those they work correctly. After I login, the JWT tokens are correctly stored to the httpOnly cookies, but I do see the “Loading…” page until I manually refresh the page, then I see my protected routes. I was thinking maybe the authentication check is firing too quickly and the state isn't ready yet and it gets stuck on the "Loading..." screen? But I'm unsure how to fix that if it's the case... I'll post the relevant code below, but I'll also share the github repo here. Here’s the browser/server consoles when going to a page … -
What is a better way to push updates to a .exe file on Client Machine? (Exe created by pyinstaller)
Context For a bit of a context I am a self taught developer who is currently working as a freelancer on Fiverr. I work using the Django and the React Framework. I develop different kinds of Automation Softwares for my clients, most of Initially, I used to deliver source code to my clients and they used to install Python and than the libraries to get the program working on their side and as you all can guess this method was very inefficient. So, I learned a trick to convert my django code into .exe format using Pyinstaller. So, now all the clients have to do is to doouble click the exe file which launches the web app in their browser. Problem But now I am facing another problem. As, I am now dealing with some repeating clients who are often contacting me to add features. But now the problem is that every time I update their web apps to add new features they all have to manually install the new version and than shift all the data manually to the newer version which is a big problem ofcourse. So, some of them are asking me to do something so that … -
Django 5.x: directory /workspace/staticfiles does not exist
I am trying to deploy an application in DO App platform and everything worked as expected. As a more stable media and static files handling I am trying to implement DO spaces to store static and media files. Here is how my settings look like for that: MEDIA_ROOT = BASE_DIR / 'media' AWS_S3_CUSTOM_DOMAIN = os.environ.get('AWS_S3_CUSTOM_DOMAIN', 'your_access_key_id') AWS_S3_FILE_OVERWRITE = False AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', 'your_access_key_id') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', 'your_secret_access_key') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', 'bucket_name') AWS_REGION = os.environ.get('AWS_REGION', 'region') AWS_S3_ENDPOINT_URL = AWS_S3_CUSTOM_DOMAIN STORAGES = { "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "access_key": AWS_ACCESS_KEY_ID, "secret_key": AWS_SECRET_ACCESS_KEY, "endpoint_url": AWS_S3_ENDPOINT_URL, "region_name": AWS_REGION, "default_acl": 'public-read', "querystring_auth": False, }, }, "staticfiles": { "BACKEND": "storages.backends.s3.S3StaticStorage", "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "access_key": AWS_ACCESS_KEY_ID, "secret_key": AWS_SECRET_ACCESS_KEY, "endpoint_url": AWS_S3_ENDPOINT_URL, "region_name": AWS_REGION, }, }, } STATIC_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.{AWS_REGION}.digitaloceanspaces.com/static/' MEDIA_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.{AWS_REGION}.digitaloceanspaces.com/media/' STATIC_ROOT = BASE_DIR / 'static' But When I deploy it I keep getting: directory /workspace/staticfiles does not exist How do I solve it? Thanks I went to digital oceans deployment guides and also searched through stackoverflow and reddit but no luck. -
Python Django Annotations over multiple relationships
I have a question On Django annotations. Here is my model: class Asset(models.Model): security = models.ForeignKey(Security, on_delete=models.CASCADE, blank=False) class Batch(models.Model): fk_asset = models.ForeignKey(Asset, on_delete=models.CASCADE, blank=False) class BatchPosition(models.Model): fk_batch = models.ForeignKey(Batch, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=14, decimal_places=2, blank=False) In my view I would like to annotate the total Sum of Batchposition->quantity to the Asset I tried things like Asset.objects.annotate(Sum("batch")).annotate(Sum("batchposition__quantity")) ...but can't get it to work. What am I doing wrong here? Is it finally possible to achieve this? -
How to fetch different data in a single template ? (django)
Scenario of my project - There are different casestudies, each casestudies has different parts which will appear in accordions, now i have designed the database and its generating dynamic accordions with respect to the number of my data entries. Each part (accordion) has two column , first ccolumn for text data second column is for media data. Each part has different format of data, how to fetch the data into this single template ? MODELS # Create your models here. 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_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) 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_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) # 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) VIEWS def casestudy(request, CaseStudy_id ): casestudy_object = get_object_or_404(CaseStudy_List, CaseStudy_id = CaseStudy_id) #for list casestudy_parts_obj = CaseStudy_Parts.objects.filter(case_study=casestudy_object).order_by('CaseStudy_order').distinct() #for accordians parts_data = [] #storing in a singlist to avoid duplicacy for … -
Django errors NoReverseMatch at /comment/4
The error occurred When I tested a wrong email format.When I enter the correct email format, it runs normally and the data is stored in the background. The error details as follows: NoReverseMatch at /comment/4 Reverse for 'comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comment/(?P<post_pk>[0-9]+)$'] There are my codes: models.py from django.db import models from django.utils import timezone # Create your models here. class Comment(models.Model): name = models.CharField('名字', max_length=50) email = models.EmailField('邮箱') url = models.URLField('网址', blank=True) text = models.TextField('内容') created_time = models.DateTimeField('创建时间', default=timezone.now) post = models.ForeignKey('blog.Post', verbose_name='comments', on_delete=models.CASCADE) class Meta: verbose_name = '评论' verbose_name_plural = verbose_name def __str__(self): return '{}: {}'.format(self.name, self.text[:20]) views.py from blog.models import Post from django.shortcuts import get_object_or_404, redirect, render from django.views.decorators.http import require_POST from .forms import CommentForm @require_POST def comment(request, post_pk): post = get_object_or_404(Post, pk=post_pk) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(post) context = { 'post': post, 'form': form, } return render(request, 'comments/preview.html', context=context) urls.py from django.urls import path from . import views app_name = 'comments' urlpatterns = [ path('comment/<int:post_pk>', views.comment, name='comment'), ] _form.html <form action="{% url 'comments:comment' post.pk %}" method="post" class="comment-form"> {% csrf_token %} <div class="row"> <div class="col-md-4"> <label for="{{ form.name.id_for_label }}">{{ form.name.label }}:</label> {{ form.name … -
1 out of many calls to overridden django `Model.save()` generates a pylint `unexpected-keyword-arg` error - how do I satisfy it?
I implemented and have been using this model (super)class I created for years, and it is completely stable on an active site. I just made a small minor tweak to some completely unrelated portion of its code, and checked my work (on my machine) with the latest superlinter. Our CI tests on github currently use an old superlinter and it has never complained, so I was surprised to see a linting error on code I haven't touched in years. My model class has an overridden save() method, which adds a few extra arguments that it pops off kwargs before calling super().save(). I have a number of calls to save inside the class, and the linter is fine with thos extra arguments everywhere else, except in 1 spot (an override of from_db): @classmethod def from_db(cls, *args, **kwargs): # Instantiate the model object rec = super().from_db(*args, **kwargs) # If autoupdates are not enabled (i.e. we're not in "lazy" mode) if not cls.get_coordinator().are_lazy_updates_enabled(): return rec # Get the field names queryset_fields = set(args[1]) # field_names # Intersect the queryset fields with the maintained fields common_fields = set(cls.get_my_update_fields()).intersection(queryset_fields) # Look for maintained field values that are None lazy_update_fields = [fld for fld in common_fields … -
How can I send a PDF from Python to PHP?
I try to create a PDF file in Python and send it to PHP. When I open the PDF it's corrupted. Python code: from reportlab.pdfgen import canvas from io import BytesIO from django.http import HttpResponse def generar_pdf(): buffer = BytesIO() c = canvas.Canvas(buffer) c.drawString(50, 50, "¡Hola, mundo!") c.save() pdf_bytes = buffer.getvalue() return HttpResponse(bytes(pdf_bytes), content_type='application/pdf') pdf_response = generar_pdf() print(pdf_response) PHP code: <?php $pdf_bytes = shell_exec("python prueba.py"); header('Content-Type: application/pdf'); header('Content-Disposition: inline; filename="archivo.pdf"'); echo $pdf_bytes; ?> I got: An error occurred while loading the PDF document. -
django-channels integration tests with pytest?
I am trying to create a simple live-server style test fixture for pytest for testing with django-channels. I came up with the simplest solution: import pytest @pytest.fixture(scope="function") def channels_live_server(request): from channels.testing import ChannelsLiveServerTestCase class MyChannelsLiveServerTestCase(ChannelsLiveServerTestCase): @property def url(self): return self.live_server_url server = MyChannelsLiveServerTestCase() server._pre_setup() yield server server._post_teardown() When used, the web server starts in the background and serves the web pages just fine... except it is using "production" settings, which means the database used is NOT the test database. Any ideas how to fix this? I do realize, that multiprocessing at some later stage is using Popen and starts the server using spawn context. I am on macOS, if that matters. -
Django proyect tring to integrate asgi
I have a django proyect that works with views and django-rest-framework and now i want to add channels to it. I have a django proyect that works with views and django-rest-framework and now i want to add channels to it so my Django project could support both HTTP and WebSocket connections. My question is there is a way of doing this? I have to rewrite my proyect to use asgi?. I found that channels_redis could do the thrick but I'm not sure -
Django REST ModelViewSet view returns 404 after PATCH
I have ModelViewSet view in django rest framework project. I am trying to filter documents that are not live, I mean are not on main view. To filter I am using params: http://localhost:8000/documents?is_live=false. I have list of records. After set true on one of objects I'm getting 404 error "GET /api/documents/?is_live=false HTTP/1.1" 200 test {'pk': '2', 'partial': True} Not Found: /api/documents/2/ Not Found: /api/documents/2/ "PATCH /api/documents/2/ HTTP/1.1" 404 "GET /api/documents/?is_live=false HTTP/1.1" 200 My view's code and custom filter (django_filters) are below: class DocumentFilter(dfilters.FilterSet): is_live = dfilters.BooleanFilter(field_name='is_live') class Meta: model = Document fields = ['is_live'] class DocumentViewSet(viewsets.ModelViewSet): serializer_class = DocumentSerializer queryset = Document.objects.all() filterset_class = DocumentFilter filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend] search_fields = ['title', 'category'] ordering_fields = [ 'title', 'category', ] def update(self, request, *args, **kwargs): print("test", args, kwargs) kwargs['partial'] = True return super().update(request, *args, **kwargs) @action(detail=True, methods=['patch']) def get_queryset(self): if self.request.query_params.get('is_live'): return self.queryset.filter(is_live=False) return self.queryset.filter(is_live=True) I would like to have possibility to partial update of object on filtered view. -
how should index.html be served with django gunicorn and nginx?
my webapplication entirely dockerized and is written with a django and gunicorn backend and an nginx frontend. nginx is needed as a proxy and to serve static files. nginx has access to the static files via mounted volume from django. I would like the entire frontend not as django templates. i'm not understanding if index.html can be directly managed by nginx like this first configuration. (first nginx.conf) or if the request should regardless firstly reach django and then, ascertained that the wanted file is a static file (index.html), be redirected with the url changed in /static/... so that can be caught by nginx. (second nginx.conf). Thanks for everyone that will eventually help me. Sorry if maybe my question is born out of ignorance and please feel free to teach me if needed. server { listen 443 ssl; bash Copy code # SSL/TLS configuration ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; # Define the location of static files location / { root /var/www/html/static/; index index.html; } location /api/ { include proxy_params; proxy_pass http://backend:8000; } location /static/ { alias /var/www/html/static/; } } server { listen 443 ssl; bash Copy code # SSL/TLS configuration ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; # Define the location of static files location … -
How to fix Gunicorn Timeout error in Django?
My Django app uses gunicorn as server. It allows users to upload files. Recently I've been getting the following error with some file uploads: 0%| | 0/1121 [00:00<?, ?frames/s][2024-06-19 18:59:53 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) 0%| | 0/1121 [00:06<?, ?frames/s] web-1 | [2024-06-19 13:59:53 -0500] [7] [INFO] Worker exiting (pid: 7) web-1 | [2024-06-19 18:59:53 +0000] [1] [ERROR] Worker (pid:7) exited with code 1 web-1 | [2024-06-19 18:59:53 +0000] [1] [ERROR] Worker (pid:7) exited with code 1. web-1 | [2024-06-19 18:59:53 +0000] [32] [INFO] Booting worker with pid: 32 Sometimes(even for the same file) I get the following error instead: [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 | … -
problem with leaving dynamic form in django
[enter image description here](https://i.sstatic.net/cwRzZ7Kg.png) I want the person to select the category in which they are going to post in order to render the form for that category, so far ok, but when they fill it out and press submit, nothing happens, why is this happening? I want the person to select the category in which they are going to post in order to render the form for that category, so far ok, but when they fill it out and press submit, nothing happens, why is this happening? -
how to display algorithm outputs from vs-code terminal into the pages of my webapp?
I have a python program in my Django app called grouping.py, I want to display the outputs of the program into my pages of my webapp.The program works as I want in the vs-code terminals but when I run the command python manage.py runserver in my CMD it displays the error File "C:\Users\aqa\Desktop\academic\academic_balancing\urls.py", line 9, in <module> path('',views.algorithm_output ,name='algorithm_output'), ^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'views' has no attribute 'algorithm_output' I tried the following : urls.py from django.urls import path import views urlpatterns = [ #algorithm template path('',views.algorithm_output ,name='algorithm_output'), ] views.py from django.shortcuts import render from grouping import form_groups # Create your views here def algorithm_output(request): #call algorithm frunction output = form_groups #pass output to the template return render(request,'academic_balancing/academic.html',{'output':output}) academic.html <!DOCTYPE html> <html> <body> <p>{{output}}</p> </body> </html> i need help to display the algorithm output to my django webapp pages -
When I try to install psycopg2-binary in my windows machine it throws error
I was trying to install the libraries from a requirements.txt file, and it throws below error. requirements.txt - psycopg2-binary==2.9.1 The Error Message looks like, Collecting psycopg2-binary==2.9.1 (from -r requirements.txt (line 6)) Using cached psycopg2-binary-2.9.1.tar.gz (380 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: psycopg2-binary Building wheel for psycopg2-binary (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for psycopg2-binary (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [20 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\errors.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\extras.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\pool.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\sql.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\tz.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\_ipaddress.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\_json.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\_range.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\__init__.py -> build\lib.win-amd64-cpython-312\psycopg2 running build_ext building 'psycopg2._psycopg' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2-binary Failed to build psycopg2-binary ERROR: Could not build wheels for psycopg2-binary, … -
Issues in Debugging a Dockerized Web App in VS Code
I am learning web development on my own through different youtube videos and books. I am using VS code and started building my own web app in Docker containers (read somewhere regarding benefits of using containers) . I have built a few apps within the project, however, as the apps are getting complex and complex it is difficult for me to debug the app for errors and see where am I going wrong. I am going to lay down the code I am using for docker files and task.json and launch.json. DOCKERFILE # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3-slim EXPOSE 8000 # Expose port for debugpy EXPOSE 5678 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install debugpy for debugging RUN python -m pip install debugpy # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser … -
How to disable verification peer in Django
In localhost my configuration works fine but in production i recieve a "Connection unexpectedly closed" error This is my configuration... EMAIL_HOST='xxxxxxx' EMAIL_PORT=25 EMAIL_HOST_USER='xxxxxxx' EMAIL_HOST_PASSWORD='xxxxxxx' DEFAULT_FROM_EMAIL=EMAIL_HOST_USER EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' -
Wrong path for my default image Django app
i'm making a music streaming website with Django and i want to display the playlists in the homepage. All is working exept for the palylists in which i didn't upload an image. I set a playlist default image but the browser doesn't find the default image because of the wrong path. How can i fix it? (Probably it's an easy thing but i'm new to Django...) html: {% for playlist in my_playlists %} <a href="{% url 'music:playlist' playlist.playlist_id %}"><img src="{{ playlist.image.url}}" alt="playlist image"></a> {% endfor %} models.py: 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="images/music-placeholder.png") plays = models.IntegerField(default=0) songs = models.ManyToManyField(Song, related_name='playlist') slug = models.SlugField() views.py: def homepage(request): songs = Song.objects.all() user = request.user if user.is_authenticated: my_playlists = Playlist.objects.filter(user=user) return render(request, 'homepage.html', {'songs': songs, 'my_playlists': my_playlists}) setting.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I got this error: Not Found: /media/media/images/music-placeholder.png but the path should be this /media/images/music-placeholder.png: -
How can I output a selection of Blog objects in a ListView in Django searched via ForeignKeys of two other different models?
I have three models like this: 1: class Blog(models.Model): title = models.CharField() published = models.DateField() ... 2: class AuthorList(models.Model): blog = models.ForeignKey(Blog) author = models.ForeignKey(User) lastTimeEdited = models.DateTimeField() ... 3: class CommentsList(models.Model): blog = models.ForeignKey(Blog) commentAuthor = models.ForeignKey(User) commentPosted = models.DateTimeField() ... My class based ListView looks like this: class DashboardView(LoginRequiredMixin, ListView): model = Blog template_name = 'app/dashboard.html' paginate_by = 5 def get_queryset(self) -> QuerySet[Blog]: user = self.request.user author = #HERE I want a queryset of all blogs, where the requested user is one of the authors. commentator = #HERE I want a queryset of all blogs, where the requested user is one of the commentators. blogs = author|commentator return blogs.order_by(#HERE I want to order them by the lastTimeEdited-Field or the commentPosted-Field) So I want to list all the blogs that the user has to do with in one way or another. I also want to order them by the lastTimeEdited value if the user is an author or by the commentPosted value if the user is a commenter. How can I do that? I've already looked for the solution in other posts, but couldn't find the right solution for my problem. -
Django timeslots not showing up in form
I am trying to build a Django booking system where I am trying to implement the logic that if a timeslot is booked for a certain day, that timeslot should not be clickable (disabled). And beside the timeslot it should read (booked). This is my implementation. But my logic is not working. No timeslots are showing up. Can anyone help me point out the problem here? Thanks! My models.py: class Timeslot(models.Model): start_time = models.TimeField() end_time = models.TimeField() slot_text = models.CharField(max_length=100) def __str__(self): return self.slot_text class Appointment(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=20) email = models.EmailField() date = models.DateField() timeslot = models.ForeignKey(Timeslot, on_delete=models.CASCADE) booked_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name} - {self.date} - {self.timeslot.slot_text}" My views.py: def check_availability(date): timeslots = Timeslot.objects.all() booked_timeslots = Appointment.objects.filter(date=date).values_list('timeslot', flat=True) available_timeslots = [(timeslot, timeslot.id not in booked_timeslots) for timeslot in timeslots] return available_timeslots def book_appointment(request): available_timeslots = [] form_data = {} if request.method == 'POST': name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') date = request.POST.get('date') timeslot_id = request.POST.get('timeslot') form_data = { 'name': name, 'phone': phone, 'email': email, 'date': date, 'timeslot': timeslot_id, } if 'check_timeslots' in request.POST: if date: available_timeslots = check_availability(date) else: messages.error(request, 'Please select a date to check available timeslots.') elif 'book_appointment' in …