Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to test multiple test files with multiple test classes but PyTest doesn't recognize other files
I've been scouring all over the internet in order to find solution for this problem. I've been trying to make sure that PyTest recognizes multiple test files to account for the multiple test files and the classes inside them in order to build a full test suite. Here's the config file: [pytest] asyncio_mode=auto asyncio_default_fixture_loop_scope="class" DJANGO_SETTINGS_MODULE = personal_blog.settings testpaths = tests Here's the test class that it recognizes: test_members.py import pytest import factory from django.contrib.auth import get_user_model from factories import MemberFactory from faker import Faker from django.urls import reverse from django.contrib.auth.models import Permission fake = Faker() # Create your tests here. User = get_user_model() # Basic Tests class TestMembers: #Confirms that a user has been created @pytest.mark.django_db def test_if_user_exists(db): user = MemberFactory() assert user.username is not None assert user.email is not None # Checks if the password fails @pytest.mark.django_db def test_set_check_password_fail(db): # basic_user.set_password("password") user = MemberFactory() assert user.password != 'Wrong' # Checks if the password fails @pytest.mark.django_db def test_set_check_password_success(db): user = MemberFactory() assert user.password == 'password' # Checks if the user is not a contributor by default. @pytest.mark.django_db def test_is_not_contributor_by_default(db): user = MemberFactory() assert user.is_contributor is False # Checks if the User is a contributor @pytest.mark.django_db def test_is_contributor(db): user = MemberFactory(is_contributor … -
Django Static Image Not Displaying When Using Variable for Image Path
I'm trying to load and display a static image in a Django template. I have a dictionary named post that contains an image value, for example, "mountain.jpg". I checked, and the dictionary has the correct data. However, when I try to set the image path dynamically using post.image, the image is not displayed. If I hardcode the URL, the image shows up correctly. Here is my image tag in the template // not working <img src="{% static "blog/images/"|add:post.image %}" alt="Mountain" /> // working <img src="{% static "blog/images/mountain.jpg" %}" alt="Mountain" /> -
Why does VScode keep popping the "SyntaxError" message, even before i am done typing?
syntax error massage, this is the error message suggestions that keeps popping up and interrupting my code flow, most times i have to comment my lines of code, and that is not ideal, so removing it would be the best. i tried going to settings to look for it , but could not find anything. I even had to go to the Json file, but to no avail, i really need help soonest -
Can I reuse output_field instance in Django ORM or I should always create a duplicate?
I have a Django codebase that does a lot of Case/When/ExpressionWrapper/Coalesce/Cast ORM functions and some of them sometimes need a field as an argument - output_field. from django.db.models import FloatField, F some_param1=Sum(F('one_value')*F('second_value'), output_field=FloatField()) some_param2=Sum(F('one_value')*F('second_value'), output_field=FloatField()) some_param3=Sum(F('one_value')*F('second_value'), output_field=FloatField()) some_param4=Sum(F('one_value')*F('second_value'), output_field=FloatField()) some_param5=Sum(F('one_value')*F('second_value'), output_field=FloatField()) Sometimes I find myself wondering why am I always creating the same instance of any Field subclass over and over again. Is there any difference if I just pass one instance and share it between expressions? F.E from django.db.models import FloatField, F float_field = FloatField() some_param1=Sum(F('one_value')*F('second_value'), output_field=float_field) some_param2=Sum(F('one_value')*F('second_value'), output_field=float_field) some_param3=Sum(F('one_value')*F('second_value'), output_field=float_field) some_param4=Sum(F('one_value')*F('second_value'), output_field=float_field) some_param5=Sum(F('one_value')*F('second_value'), output_field=float_field) I coulnd't find it in a documentation and the source code is not documented well regarding this parameter. P.S. The example is fake, just imagine a big annotate function that does a lot of processing using Case/When/ExpressionWrapper/Coalesce/Cast and has a lot of duplicated Field instances as output_field. -
Discrepancy in Record Count Between Django ORM and Raw SQL Query
I'm encountering an issue where the count of records returned by a Django ORM query does not match the count returned by a raw SQL query. Here is the relevant part of my Django view: start_date = datetime(2024, 10, 19, 0, 0, 0) end_date = datetime(2024, 10, 19, 23, 59, 59) dbug = Reservations.objects.all().filter(updated_at__range=(start_date, end_date)) print(dbug.count()) Above returns 6529 The Django settings.py contains: TIME_ZONE = 'Asia/Tehran' USE_TZ = False I have tried SQL query same bellow: SELECT COUNT(*) FROM "consultant_reservations" WHERE updated_at BETWEEN '2024-10-19 00:00:00' AND '2024-10-19 23:59:59'; count ------- 6540 (1 row) Here is discrepancy within SQL query result (which is 6540) I have tried in psql terminal and Django ORM result (which is 6529) Please let me presenting an example: Trying SQL query same as: SELECT * FROM "consultant_reservations" WHERE updated_at BETWEEN '2024-10-19 00:00:00' AND '2024-10-19 23:59:59' LIMIT 4; Result: id | idd | voip_number | client_id | client_mobile | reserve_duration | status | reserve_timestamp | created_at | updated_at | consultant_id_id | mobile_id | created_by | updated_by -------+---------+-------------+-----------+---------------+------------------+----------+------------------------+------------------------+------------------------+------------------+-----------+------------+------------ 76407 | 2011050 | 2217 | 1101151 | 09355648120 | 3600 | reserved | 2024-10-19 19:30:00+00 | 2024-10-14 08:40:03+00 | 2024-10-19 20:28:01+00 | 5052 | 2395781 | 3445 | 0 … -
Are consecutive django model save calls safe?
I'm having trouble with a field that seems to sometimes not update. Just want to know if the following is unsafe on a Django model instance. obj.field1 = True obj.save() obj.field2 = True obj.save() Since I'm not calling obj.update_from_db() is there any risk the second save resets/overrides field1 ? There are no post_save hooks involved, the surrounding code is synchronous and the DB backend is PostgreSQL. Also, is save() synchronous (in the sense that the DB update will happen before the function returns)? -
WebSocket Connection Issue with Django Channels in Gunicorn
I tried to implement live chat using Django Channels and Daphne. It works fine on my local server, but now I want to implement it in production using Gunicorn, nginx. However, when I reload and restart the and run, I'm getting an error (as shown in the image below) it in service. I tried modifying my services, but it still doesn't work. I can't figure out the cause since there is no specific error. Can someone help me with this? Any ideas would be much appreciated this is what I tried Service Gunicorn [Unit] Description=Tris application daemon services Requires=tev.socket After=network.target [Service] User=dswdcaraga Group=www-data WorkingDirectory=/opt/apps/tev Environment=DJANGO_SETTINGS_MODULE=tev.settings ExecStart=/opt/apps/env/bin/daphne -u /run/tev/tev.sock tev.asgi:application --bind 0.0.0.0:8000 [Install] WantedBy=multi-user.target Nginx server { server_name caraga-tris-staging.dswd.gov.ph; listen 80; return 301 https://caraga-tris-staging.dswd.gov.ph$request_uri; } server { server_name caraga-tris-staging.dswd.gov.ph; listen 443 ssl; #ssl_certificate /etc/ssl/certs/caraga/server-cer.pem; #ssl_certificate_key /etc/ssl/certs/caraga/server-key.key; ssl_certificate /etc/ssl/certs/caraga/ssl_nginx/server-cer.pem; ssl_certificate_key /etc/ssl/certs/caraga/ssl_nginx/server-key.key; location / { include proxy_params; proxy_pass http://unix:/run/tev/tev.sock; #WebSocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } proxy_headers_hash_max_size 1024; proxy_headers_hash_bucket_size 128; asgi.py configuration import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter #from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from main import routing import main.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tev.settings') django.setup() … -
How to run a Python Django project that is deployed on a local machine?
I attempted to run a deployed Django project on my local machine by setting up a virtual environment and installing all required dependencies. I also modified the production.py settings, specifically the ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS, to include local addresses like http://127.0.0.1:8000. However, despite these changes, the project only displayed a public IP and did not allow me to access it locally. I would like guidance on additional adjustments needed in the production.py or elsewhere to successfully run the project on my local machine. -
Django - TemplateDoesNotExist at /accounts/login/
I have looked at similar posts, but am really struggling with templates and urls.py - at least thats where I think my problem is. I'm trying to use the default login page that comes with django. I get this error message, I've tried so many things but still cannot not get to work, can some please help? This is the error message: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://134.209.220.170/accounts/login/?next=/timwise/upload/ Django Version: 5.0 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: /usr/local/lib/python3.10/dist-packages/django/template/loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: /usr/bin/python3 Python Version: 3.10.12 Python Path: ['/home/django/django_project', '/usr/bin', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Wed, 23 Oct 2024 01:53:02 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/django/django_project/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.10/dist-packages/django/contrib/admin/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.10/dist-packages/django/contrib/auth/templates/registration/login.html (Source does not exist) this is the template area of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [BASE_DIR, "/home/django/django_project/templates"], 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] this is my class view that is trying to redirect to the default django login page: class FileUploadView(LoginRequiredMixin, CreateView): #entire … -
Django TypeError: Cannot filter against a non-conditional expression while filtering by foreign key
I've looked through multiple similar questions, but couldn't get the logic, and my manipulations were unsuccessful. I have a forum app, its structure is "forum->subforum->topic->comments", corresponding models for subforums, topics and comments. I have to implement a filter on each subforum page (where the list of corresponding topics is displayed), by which I can configure the search of/among the topics by several conditions. Particularly I have to implement a custom filter, and my idea was to create a filter for empty topics, that is, for topics only with initial comments and without responses. Through a desperate struggle I've finally understood how to implement reversed foreign key connection in querysets, but now I can't use a queryset expression as a filter, as it returns TypeError: Cannot filter against a non-conditional expression. Here are the specifics: filters.py: import django_filters from django.db.models import Count from forum.models import Topic class TopicFilter(django_filters.FilterSet): date_span = django_filters.DateRangeFilter(field_name='created', label='Период создания') comments = django_filters.CharFilter(field_name='comment__content', lookup_expr='icontains', label='Комментарии') subject = django_filters.CharFilter(lookup_expr='icontains', label='Тема обсуждения') creator = django_filters.CharFilter(field_name='creator__username', lookup_expr='icontains', label='Создатель темы') is_empty = django_filters.BooleanFilter(method='filter_empty', label='Темы без комментариев') class Meta: model = Topic fields = ['subject', 'creator', 'date_span', 'comments', 'is_empty'] def filter_empty(self, queryset, value): comment_count_gte_1 = Topic.objects.annotate(comment_count=Count('comments')).filter(comment_count__gte=1) comment_count_lt_1 = Topic.objects.annotate(comment_count=Count('comments')).filter(comment_count__lt=1) if value is True: … -
Optimizing Django QuerySet with Nested Aggregations
I’m working on optimizing a complex Django query where I need to perform nested aggregations and conditional annotations across multiple related models. I want to fetch the top 5 most active users based on their interactions with posts, while also calculating different types of engagement metrics (like views, comments, and likes). My models: class User(models.Model): name = models.CharField(max_length=100) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) created_at = models.DateTimeField() class Engagement(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) type = models.CharField(max_length=50) # 'view', 'like', 'comment' created_at = models.DateTimeField() Here is what my code looks like: from django.db.models import Count, Q some_date = ... top_users = ( User.objects.annotate( view_count=Count('engagement__id', filter=Q(engagement__type='view', engagement__created_at__gte=some_date)), like_count=Count('engagement__id', filter=Q(engagement__type='like', engagement__created_at__gte=some_date)), comment_count=Count('engagement__id', filter=Q(engagement__type='comment', engagement__created_at__gte=some_date)), total_engagements=Count('engagement__id', filter=Q(engagement__created_at__gte=some_date)) ) .order_by('-total_engagements')[:5] ) It works, however the query performance is not ideal. With large datasets, this approach leads to slow query execution times and I wonder whether using multiple Count annotations with filter conditions is efficient. Is there a more optimized way to write this query, or any best practices I should consider for improving performance, especially when dealing with large amounts of data? Any insights or suggestions would be really helpful! -
Django dynamically adding integer fields to forms
Hi I have a very simple application that I am making in order to learn Django. I have a SQLite table that has two columns, the first is the 'id' generated by Django, the second is a charfield containing the name of a product_name. The way I am trying to get the program to work is as follows: Get value list of values in the table. This query_set gets assigned to bases Loop through the each tuple in the bases list and use these values to create form fields. So the product_name will be the Label and the id will be the id of the field. I will later use Jquery on these fields to get the values. I have the following code: from django import forms from django.db import models from django.core.exceptions import ValidationError from .models import Department, Test_list, Products, Current_tests class Batch(forms.Form): bases = Products.objects.all().values_list('product_name','id') for i in bases: for j in [0,1]: bn = i[0] bnid = i[1] name = forms.IntegerField(label=f"{bn}",widget=forms.NumberInput(attrs={"id":bnid})) The code actually works but instead of getting a number of text inputs equal to the rows in my database, it only shows the last row. I believe this is because while in the loop, I … -
Django + jQuery: No Image Provided Error with 400 31 Response When Uploading Image via AJAX
I'm working on a Django project where I'm uploading an image to be processed by a machine learning model. The frontend uses jQuery to send the image via an AJAX request. However, the server keeps returning the error: {"error": "No image provided."} and Accuracy: NaN%. Additionally, I receive the response 400 31 in the browser console. Frontend (AJAX and HTML Code): <script> $(document).ready(() => { $("input[id='image']").on('change', function (event) { let input = this; var reader = new FileReader(); reader.onload = function (e) { $('#banner').css('width', '350px') $('#banner').addClass('img-thumbnail') $('#banner').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); }) $('#process').click(() => { $('.buttons').hide() $('.loader').show() $('#title').html("Processing...") let image = $('#image').prop('files')[0] var data = image['name']; console.log(data) $.ajax({ url: "http://127.0.0.1:8000/api/", type: "POST", dataType: 'json', data: { image: data, csrfmiddlewaretoken: '{{ csrf_token }}' }, headers: { 'Authorization': 'z*qm$(e9k0wa--t!^ux(xn15vk$)h7c$%3%vflo^@_++bg&uw(', // CSRF token 'Content-Type': 'application/json' // JSON }, success: function (xhr) { alert("Error while processing") }, error: function (xhr) { $('#title').html("Result") let result = (xhr.responseText).split("-"); let disease = result[0]; let accuracy = result[1]; $('.loader').hide() $('#disease').html("Result: " + disease) $('#accuracy').html("Accuracy: " + parseInt(accuracy).toFixed(2) + "%") $('#graph').attr('src', '{% static "graph.png" %}') $('.result').show() } }); }); }); </script> Django Views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, JsonResponse from diab_retina_app import process … -
Rendering MultiValueField including help_text and label for each subfield
I am using a JSONField to represent a config that is used in multiple forms. Instead of the default Textarea widget, I want to render multiple fields each with their own label and help_text. I am able to achieve this by implementing a Form just for the config but it seems it should also be possible (and cleaner) to represent the config as a MultiValueField. Unfortunately I cannot for the life of me figure out how to render the label and the help_text when following this approach as that information seems no longer available when the widget is rendered. What am I missing? class ConfigWidget(forms.MultiWidget): template_name = 'config_widget.html' def __init__(self, attrs=None): widgets = [ forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs), ] super().__init__(widgets, attrs) def decompress(self, value): if isinstance(value, dict): return [value['foo'], value['bar']] return [None, None] class ConfigField(forms.MultiValueField): widget = ConfigWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(label='Foo', help_text='Foo help.'), forms.CharField(label='Bar', help_text='Bar help.'), ) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): if data_list: return { 'foo': data_list[0], 'bar': data_list[1], } -
Django test client redirects logged users to login page
I know this questions has already been asked, but none of the answers works for me. Whenever I try to use the client login in Django tests, it basically gets ignored and I get a redirect to the login page. After a few test I noticed that it logs me in correctly, but kicks me out when I use it. Here is a stripped down version of my code that still reproduces this. from django.auth import get_user() class MapListViewTest(TestCase): @classmethod def setUpTestData(cls): # Create a user cls.user = get_user_model().objects.create(username="testuser") cls.user.set_password("password") cls.user.save() # [...] def setUp(self): self.client.login( username=self.user.get_username(), password=self.user.password ) def test_map_list_view_renders(self): """Test that the MapListView renders successfully and includes a list of maps.""" logger.info(get_user(self.client)) # <-- <django.contrib.auth.models.AnonymousUser object at 0x7377d5589540> self.client.login( username=self.user.get_username(), password=self.user.password ) logger.info(get_user(self.client)) # <-- <Profile: testuser> response = self.client.get(reverse("map_list"), follow=True) logger.info(get_user(self.client)) # <-- <django.contrib.auth.models.AnonymousUser object at 0x7377d5589540> self.assertEqual(response.status_code, 200) # <-- OK self.assertTemplateUsed(response, "map_list.html") # <-- lands on 'account/login.html' (I put it twice here in the snippet, but it is only in the setUp in the real code) I don't know if this is of any relevance, but the redirection changes the address from http://localhost/... to http://testserver/..., and I am working in a docker container. Also, the … -
Save number of total search query count on models in Django
Below is my Django code to save user searches on database. How can I implement a function that when a same user searches same keywords for multiple time I need to record count of that keywords on database if its logged in user or session user def get_queryset(self): query = self.request.GET.get('q') if query: if self.request.user.is_authenticated: if not search_keywords.objects.filter(user=self.request.user, search_word=query).exists(): search_keywords.objects.create( user = self.request.user, search_word = query, session_id = session_id ) else: if not search_keywords.objects.filter(session_id=session_id, search_word=query).exists(): search_keywords.objects.get_or_create( session_id=session_id, search_word = query, ) search_vector = ( SearchVector('title', weight='A') + SearchVector('description', weight='B') + ) search_query = SearchQuery(query) return items.objects.annotate( rank=SearchRank(search_vector, search_query) ).filter(rank__gt=0.1).order_by('-rank') return items.objects.none() -
Token authentication not working in Django Rest Framework after passing the token
Session authentication is working correctly as I am getting "You are authenticated!" if I login from the Django admin, but token authentication isn't functioning and I am getting error "Authentication credentials were not provided." pip freeze Django==5.1.2 django-filter==24.3 djangorestframework==3.15.2 djangorestframework-simplejwt==5.3.1 Following are the project files views.py from django.shortcuts import render from rest_framework import generics, permissions from .models import Artist from .serializers import ArtistSerializer from rest_framework.authentication import TokenAuthentication class ArtistListCreateView(generics.ListCreateAPIView): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = [permissions.IsAuthenticated] authentication_classes = [TokenAuthentication] def perform_create(self, serializer): serializer.save(user=self.request.user) class ArtistDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): print("Authenticated user:", self.request.user) return Artist.objects.filter(user=self.request.user) serializers.py from rest_framework import serializers from .models import Artist class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = ['id', 'user', 'phone_country_code', 'phone', 'location', 'created_at', 'updated_at'] read_only_fields = ['id', 'user','created_at', 'updated_at'] models.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Artist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='artist_profile') phone_country_code = models.CharField(max_length=10) phone = models.CharField(max_length=15) location = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username urls.py from django.urls import path from .views import ArtistListCreateView, ArtistDetailView urlpatterns = [ path('artists/', ArtistListCreateView.as_view(), name='artist-list-create'), path('artists/<int:pk>/', ArtistDetailView.as_view(), name='artist-detail'), ] I have tried updating the settings.py with following details … -
SSL is required, but the server does not support it (Django)
I was working on a test project as a practice and when I tried migrating it to the database (MariaDB PhpMyAdmin), I get this error "django.db.utils.OperationalError: (2026, 'TLS/SSL error: SSL is required, but the server does not support it')" This is how I wrote it in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'schooldb', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3307', # 'OPTIONS': {'init_command': "SET SQL_MODE='STRICT_TRANS_TABLES'"}, } } I already have mysqlclient installed. -
Python requests Session not passing cookies?
I have followed the documentation as far as I can tell, but it seems that the requests library Session object is not retaining cookies. Here is my simple code: with requests.Session() as s: url = '%s://'%http+serverStr+'/login/' s.get(url) payload = {'username': 'sfprod', 'password': <password>, 'csrfmiddlewaretoken': s.cookies['csrftoken'], 'next': '/'} login_resp = s.post(url, data=payload, headers=(dict(Referer=url))) This is connecting to a Django server. When I run the first s.get() call I see these cookies returned: <RequestsCookieJar[Cookie(version=0, name='csrftoken', value='Iw2k4RF5QIy6oNOA71681oq4kGVBxjzTmQCULicbWdr5ZfH1Kunrn30DNupQtFhF', port=None, port_specified=False, domain='gancho.local', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=True, expires=1761043315, discard=False, comment=None, comment_url=None, rest={'SameSite': 'Lax'}, rfc2109=False)]> However when the second call happens, no cookies are passed to the server. The COOKIES member of the request object received is empty and the server returns 403 Forbidden. I stepped through the csrftoken code in the debugger and it is rejecting the request because the cookie is not present (to be precise, because there is no CSRF_COOKIE value in the META member of the request, but I assume this is because the cookie is not present). I can log in with a browser, and in this case I see the cookie in the request, so I think it is not a setup problem with the server. Is there something I … -
Is it safe and ok to divide mp3 file like that?
I have an mp3 file and want to divide it into several files ("chunks"). I came up with this code (I stole the idea from django): from pathlib import Path class FileWrapper: def __init__(self, file) -> None: self.file = file def chunks(self, chunk_size): chunk_size = chunk_size try: self.file.seek(0) except (AttributeError, Exception): pass while True: data = self.file.read(chunk_size) if not data: break yield data with open("./test2.mp3", "rb+") as src: wrapper_file = FileWrapper(src) for chunk_ind, chunk in enumerate(wrapper_file.chunks(chunk_size=100 * 1024)): out_file_path = Path("./", f"test2_{chunk_ind}.mp3") with open(out_file_path, "wb+") as destination: destination.write(chunk) And, you know, it's working okay, but I'm scary and in doubt, that this approach can sometimes work, but sometimes it maybe can "brake" resulted "chunks". So, is this way - okay? Or I need to dive deeper into how mp3 files made? -
"GET /static/assets/css/plugins/something.css.map HTTP/1.1" 404
I am getting this error every time I reload my website. And for this error it's taking so much time to reload the website. but my stylings from .css and .js are working. I am getting this errors in my terminal - [22/Oct/2024 03:51:18] "GET /static/assets/css/demos/demo-6.css HTTP/1.1" 304 0 [22/Oct/2024 03:51:18] "GET /static/assets/css/custom-old.css HTTP/1.1" 304 0 **[22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/jquery.countdown.css.map HTTP/1.1" 404 1989 [22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/magnific-popup/magnific-popup.css.map HTTP/1.1" 404 2028 [22/Oct/2024 03:51:20] "GET /static/assets/css/style.css.map HTTP/1.1" 404 1932 [22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/owl-carousel/owl.carousel.css.map HTTP/1.1" 404 2016 [22/Oct/2024 03:51:20] "GET /static/assets/css/demos/demo-6.css.map HTTP/1.1" 404 1953 [22/Oct/2024 03:51:20] "GET /static/assets/css/skins/skin-demo-6.css.map HTTP/1.1" 404 1968 [22/Oct/2024 03:51:20] "GET /static/assets/css/bootstrap.min.css.map HTTP/1.1" 404 1956 [22/Oct/2024 03:51:20] "GET /static/assets/js/bootstrap.bundle.min.js.map HTTP/1.1" 404 1971 [22/Oct/2024 03:51:20] "GET /static/assets/js/jquery.plugin.min.map HTTP/1.1" 404 1953 [22/Oct/2024 03:51:20] "GET /static/assets/js/jquery.countdown.min.map HTTP/1.1" 404 1962** I am using soome jquery plugins. Here's i am linking the files in my base.html CSS - <link rel="stylesheet" href="{% static 'assets/css/style.css'%}"> <link rel="stylesheet" href="{% static 'assets/css/skins/skin-demo-6.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/demos/demo-6.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"> <link rel="stylesheet" href="http://dodsoftware.com/sotests/fancy/jquery.fancybox-1.3.4.css" type="text/css" media="screen" /> <link rel="stylesheet" href="{% static 'assets/css/custom-old.css'%}"> <link rel="stylesheet" href="{% static 'assets/css/custom.css'%}"> JAVASCRIPTS - <script src="{% static 'assets/js/jquery.elevateZoom.min.js' %}"></script> <script src="{% static 'assets/js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'assets/js/jquery.plugin.min.js' %}"></script> <script src="{% static 'assets/js/jquery.countdown.min.js' … -
mysqlclient not found even after installed in Django on MacOS
I use pyenv to create a virtual-env, and install mysqlclient in it successfully. But when I python manage.py runserver, it shows 'Did you install mysqlclient?'. How to resoleve it? I try it both in terminal and PyCharm, all did not work. I also looked up a lot of technical forums and basically said that the virtual environment mismatch is the reason, and no one is in the same situation as me. -
How do I avoid a SuspiciousFileOperation when uploading a Django photo?
from django_resized import ResizedImageField class UserProfilePhoto(Model): photo = ResizedImageField(size=[128, 128], upload_to=MEDIA_ROOT) photo_hash = BigIntegerField( blank=True, null=True, help_text=_("an integer representation of the hexdigest hash of the photo"), ) def __str__(self): return f"{self.photo.name} ({self.photo_hash})" I used to have a save() operation in the model, which would do the resizing but now I'm using Django-resized because after all that figuring out how to resize the photo and generate a hash value it turns out there is a module to do it already. I'm adding a picture to the userprofilephoto in the admin. SuspiciousFileOperation at /admin/userprofile/userprofilephoto/add/ Detected path traversal attempt in '/app/mine/media/mendlebrot-lawn.jpeg' How do you turn off the error or the validation? To answer some questions in advance: No. I'm not going to go back to ImageField() It gave me the same problem with lots more code. -
how to fix my register view that generates a token and assigns it to a cookie? django error
Hello I am having trouble building a register view for my django homework assignment. I'm a beginner and trying to work on my register functionality and the views file is where I am having trouble. It's supposed to add a new user to user table in the database, and create a session key string and assign it to the cookie so the user can stay signed in. Whenever I submit a new user it redirects and gives me this error ValueError: Field 'id' expected a number but got 'pjtjtksydunpdysgxcxtmpazfyawvqzg' (my generated string) Here's my register view def register(request: HttpRequest): if request.method == 'POST': params = request.POST user = User( name = params.get("name"), email = params.get("email"), password_hash = params.get("password") ) hasher = hashlib.sha256() hasher.update(bytes(user.password_hash, "UTF-8")) user.password_hash = hasher.hexdigest() user.save() token = "" letters = string.ascii_lowercase for _ in range(32): token = "".join(random.choice(letters) for _ in range(32)) session_token = Session.objects.create(user=user, token=token) response = redirect("/") response.set_cookie('token', token) return response return render(request, "destination/register.html") here are my models in case if needed class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() email = models.EmailField(unique=True) password_hash = models.TextField() class Session(models.Model): id = models.BigAutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.TextField() register.html <!DOCTYPE html> <html lang="en"> <head> <meta … -
Excel File Corrupted When Downloaded from Django Backend via Axios in Vue.js
I'm trying to download an Excel file from my Django backend to the frontend using Axios and FileSaver.js (also tried without this). The file is generated successfully on the backend, but when I download it through the frontend, the file becomes corrupted and cannot be opened by Excel. I am using pandas to create the Excel file in-memory and then return it as a response. Backend code - buffer = BytesIO() with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer: for item in data_list: attributes = item['attributes'] attributes['ID'] = item['id'] df = pd.DataFrame([attributes]) sheet_name = f"Sheet_{item['id']}" df.to_excel(writer, sheet_name=sheet_name, index=False) buffer.seek(0) response = HttpResponse(buffer, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="data_export.xlsx"' return response Frontend code - async function downloadFile() { try { const response = await axios.get('/api/export-excel', { responseType: 'blob', }); saveAs(new Blob([response.data]), 'data_export.xlsx'); } catch (error) { console.error('Error downloading file:', error); } } I know there are similar questions already asked and I have already tried those things (using arraybuffer, type - ms-excel, also tried using openpyxl) but none seems to work. What could be causing the file corruption during download via the frontend? How can I ensure that the file downloads correctly and opens in Excel without corruption? Any advice or suggestions would be greatly …