Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object of type ListSerializer is not JSON serializable
I want to Serialize a Django model and Show it as a DRF Response and Im facing this error many times here is my API view: class ListCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request: HttpRequest) -> Response: comments = Comment.objects.all() serialized_comments = CommentModelSerializer(instance=comments, many=True) return Response(serialized_comments) here is my model: class Comment(models.Model): RATES: list[tuple[int, str]] = [ (1, 'Worst'), (2, 'Meh'), (3, 'Best'), ] user = models.ForeignKey(to=User, default=None, blank=True, on_delete=models.CASCADE ,verbose_name='User') text = models.TextField(max_length=200, default=None, blank=True, verbose_name='Comment') rate = models.IntegerField(choices=RATES, default=None, blank=True, verbose_name='Rate') viewed_by_admin = models.BooleanField(default=False, blank=True, verbose_name='Viewed By Admin') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created at') updated_at = models.DateTimeField(auto_now=True, verbose_name='Updated at') def __str__(self) -> str: return str(self.user) class Meta: verbose_name = 'Comment' verbose_name_plural = 'Comments' here is my serializer: from rest_framework import serializers from comment.models import Comment class CommentModelSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['text', 'rate'] so I tried many things but it didn't work and I don't know what to do and I would appreciate a little help -
Error while adding an image to the db using django panel in production. Using docker, nginx and gunicorn
I did a page with django which give the possibility to the user to access to the django admin panel to add an image into the page. The image is being pull to the database with the models of django. class Images(models.Model): left_arrow= models.ImageField(upload_to="general/arrow/") right_arrow= models.ImageField(upload_to="general/arrow/") open_complete= models.ImageField(upload_to="general/complete/") close_complete= models.ImageField(upload_to="general/complete/") untick= models.ImageField(upload_to="general/tick/") tick= models.ImageField(upload_to="general/tick/") This was working perfectly in development because i had this command in the urls file: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In production i had to errase those lines. The media files that were already in the database are being showed perfectly well, the static and media files are working perfectly. But when a user tries to add an image from the django admin panel an error ocurr. 502 Bad Gateway nginx Digging into the problem i searched the logs of nginx and are the following: 2024/09/17 19:27:27 [error] code: *36 upstream prematurely closed connection while reading response header from upstream, client: "IP",server: carranzafebre.com, request: "POST /admin/home/images/add/ HTTP/1.1", upstream: "http://127.0.0.1:8000/admin/home/images/add/", host: "carranzafebre.com", referrer: "https://carranzafebre.com/admin/home/images/add/" I have already change a huge amount of things, but nothing happens with this error. Please i need help. I am ussing the default database of django which is sqlite3. I tried … -
Setup Heroku to run Django unit tests in parallel
I am currently working on a Django project and have deployed my application on Heroku. I want to optimize my CI/CD pipeline by running my Django unit tests in parallel (I'm using pytest and I'd like to keep using it). Could someone guide me on how to properly set up parallel test execution? The following is my app.json file: { ... "environments": { "review": { ... }, "test": { "scripts": { "test": "pytest -v --cov=app-name --cov-fail-under=90", "integration-test": "pytest -v -m integration" }, "env": { ... }, "formation": { "test": { "quantity": 1, "size": "standard-1x" } }, "buildpacks": [ { "url": "heroku/python" } ] } } } -
Django Admin TabularInLine bad table shown
I have a Django Admin List-Change module with a TabularInline, where the table head is shown correctly, but every row is wrong, as if it were a StackedInline. Django-admin-interca is installed, with bootstrap. why is the row width compressed? And why the head row has the first column without label? The html page on browser seems ok: -
How do I show the error to the user when initializing the Django form?
I'm trying to do the following. The form should upload a text file. If it is not present, the form should not be loaded. An error should appear instead. class SemanticAiForm(forms.Form): semantic_folder = configurate.AI_DATA_FOLDER semantic_files = 'ai_openai_fresh_news.txt' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) semantic = self.get_semantic() if semantic is None: self.add_error(NON_FIELD_ERRORS, 'No data') else: self.fields['order'] = forms.CharField(widget=forms.Textarea()) self.fields['order'].initial = semantic.system_content def get_semantic(self) -> Union[SemanticTxt, None]: """ Получает объект SemanticTxt с прочитанным файлом параметрической конфигурации. """ try: filepath = os.path.join(self.semantic_folder, self.semantic_files) semantic = read_semantic(filepath) except exception.SemanticError: return return semantic If there is a file, everything is fine. If there is no file, on the contrary. Django reports: 'SemanticAiForm' object has no attribute 'cleaned_data' I'm trying to do something else. If there is no file, display an error in the template. And don't show the form. What am I doing wrong? -
Force django not to redirect after password change?
Maybe this is a stupid question. I have a simple Django app and when I change the password (success or not) I want to stay on the same page (I wanna manage with JS the messages). So I no wanna redirect at all at path (password_change/done). Is this possible? This is the views file that I tried, I tried to return None hoping it will work. @login_required def ChangePassword(request): form = ChangePasswordForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Your password was successfully updated!') else: messages.error(request, 'something happened!') -
Why is POST request to /api/posts/ returning 401 Unauthorized in Django DRF despite valid token in Axios headers?
Problem: I'm facing an issue with a 401 Unauthorized response when making a POST request to /api/posts/ in my Django Rest Framework (DRF) backend from a React frontend. The Axios instance in React uses an interceptor to add a Bearer token (stored in localStorage) to the Authorization header, but the request still fails. The DRF view uses generics.ListCreateAPIView and requires authentication with permissions.IsAuthenticated. The POST request fails, even though the token is present in the headers. I've checked both the frontend and backend configurations, but the issue persists. The urlpattern is posts/. But from frontend it all the urlpatterns for the api(Django app) can only be accesed through /api/urlpattern/. Django DRF Backend Code models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') body = models.TextField(max_length=240) media = models.ImageField(null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) def number_of_likes(self): return self.likes.count() def number_of_comments(self): return self.comments.count() def get_created_at_in_user_timezone(self, author): user_timezone = pytz.timezone(author.profile.timezone) return self.created_at.astimezone(user_timezone) class PostSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(source='author.username', read_only=True) number_of_likes = serializers.SerializerMethodField() number_of_comments = serializers.SerializerMethodField() def get_number_of_likes(self, obj): return obj.likes.count() def get_number_of_comments(self, obj): return obj.comments.count() class Meta: model = Post fields = ['id', 'author', 'body', 'media', 'created_at', 'number_of_likes', 'number_of_comments'] read_only_fields = ['author', 'created_at', 'number_of_likes', 'number_of_comments'] class PostListCreateView(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticatedOrReadOnly] … -
What is the best way to handle potentially large file uploads in django?
I've been reading the django docs and posts here on stackoverflow but still not sure how to. So far this is my code: forms.py: def validate_file(file): # Validate if no file submitted if not file: #raise ValidationError("No file submitted") raise ValidationError("Error") # Check file size (5 GB limit) max_size = 5 * 1024 * 1024 * 1024 # 5 GB in bytes if file.size > max_size: #raise ValidationError("The maximum file size that can be uploaded is 5GB") raise ValidationError("Error") # Define allowed file types and their corresponding MIME types allowed_types = { # Audio formats 'wav': ['audio/wav', 'audio/x-wav'], 'mp3': ['audio/mpeg', 'audio/mp3'], 'mpga': ['audio/mpeg'], 'aac': ['audio/aac'], ... class UploadFileForm(forms.Form): file = forms.FileField(validators=[validate_file]) views.py: def transcribe_Submit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] session_id = str(uuid.uuid4()) request.session['session_id'] = session_id try: transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() ... modesl.py: class TranscribedDocument(models.Model): id = models.CharField(primary_key=True, max_length = 40) audio_file = models.FileField(max_length = 140, upload_to='example_upload_url/', null= True) ... This is what I've been working with but I've been reading that it is better to handle uploads as chunks so that large files don't overwhelm the website. The website uploads to directly DigitalOcean Spaces with no files stored … -
FOREIGN KEY constraint failed (IntegrityError) while adding a value to a ManyToManyField in Django
Exception Type: IntegrityError Exception Value:FOREIGN KEY constraint failed Exception Location: django/db/backends/base/base.py, line 303, in _commit Raised during: django.contrib.admin.options.change_view Here is my model class class ReviewModel(models.Model): title=models.CharField(max_length=100) description=models.CharField(max_length=200) reviewer=models.ForeignKey(UserModel,on_delete=models.SET_NULL,null=True,blank=True) class ProductsModel(models.Model): uid=models.CharField(max_length=100,primary_key=True) name=models.CharField(max_length=100) description=models.CharField(max_length=200) category=models.ForeignKey(ProductCategoryModel,on_delete=models.CASCADE) price=models.PositiveIntegerField() image1=models.ImageField(upload_to="images/products") seller=models.ForeignKey(UserModel,on_delete=models.CASCADE) reviews=models.ManyToManyField(ReviewModel,blank=False) Here is my serializer class ReviewSerializer(serializers.ModelSerializer): class Meta: model=ReviewModel fields='__all__' class ProductsSerializer(serializers.ModelSerializer): reviews = ReviewSerializer(many=True, read_only=True) class Meta: model = ProductsModel fields='__all__' depth=1 Here is my views class ProductsListView(generics.ListCreateAPIView): queryset=ProductsModel.objects.all() serializer_class=ProductsSerializer I am able to add value and save with all fields except reviews through admin panel. When I keep it blank everything goes well but on selecting any value for reviews it raise this error. I added create function in serializer but no change class ProductsSerializer(serializers.ModelSerializer): reviews = ReviewSerializer(many=True, read_only=True) class Meta: model = ProductsModel fields='__all__' def create(self, validated_data): reviews_data = validated_data.pop('reviews', []) # Handle reviews separately product = ProductsModel.objects.create(**validated_data) # If you're also creating reviews when creating a product for review_data in reviews_data: review = ReviewModel.objects.create(**review_data) product.reviews.add(review) return product -
django StreamingHttpResponse to return large files
I need to get pdf files from s3 and return the same file to the frontend. def stream_pdf_from_s3(request, file_key): s3_client = boto3.client('s3') try: response = s3_client.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=file_key) pdf_stream = response['Body'] # Use iter_chunks() for efficient streaming return StreamingHttpResponse(pdf_stream.iter_chunks(chunk_size=65,536), content_type='application/pdf') except Exception as e: return HttpResponse(f"Error fetching PDF: {e}", status=500) But in the browser's network tab, it seems that no bytes are streamed even after a longer time. The request is in pending state. The expectation was bytes soon be returned in chunks immediately. What could be the reason and is there any improper configuration with the code? -
I got an "Broken pipe" error when i try to save info in db with form on django
Im workin on a local server, this is my error: [17/Sep/2024 09:54:26,384] - Broken pipe from ('127.0.0.1', 53046) this are my models: class Personal(models.Model): T1 = 1 T2 = 2 T3 = 3 T4 = 4 TIPIFICACION_CHOICES = ( (T1, 'Personal Policial'), (T2, 'Personal Civil Nivel 1'), (T3, 'Personal Civil Nivel 2'), (T4, 'Personal Civil Nivel 3'), ) T1 = 1 T2 = 2 EDUCACION_CHOICES = ( (T1, 'Educación Secundaria'), (T2, 'Educación Superior'), ) legajo = models.IntegerField(unique=True) nombre = models.CharField(max_length=120, unique=True) apellido = models.CharField(max_length=120, unique=True) dni = models.IntegerField(unique=True) tipificacion = models.PositiveSmallIntegerField(choices=TIPIFICACION_CHOICES, default=T1) nivel_eduacativo = models.PositiveSmallIntegerField(choices=EDUCACION_CHOICES, default=T1) fecha_alta = models.DateField() posee_sancion = models.BooleanField() apto_ascenso = models.BooleanField() se_evalua = models.BooleanField() calificador = models.BooleanField() class Meta: ordering = ['apellido', 'nombre'] verbose_name = "Personal" verbose_name_plural = "Personal" def __str__(self): return f"{self.apellido}, {self.nombre}" def get_absolute_url(self): """ Devuelve la url para acceder a una instancia particular. """ return reverse('personal_update', args=[str(self.pk)]) def is_civil(self): """ Devuelve un valor booleano para comprobar si la instancia del mismo modelo es civil. """ return self.tipificacion in [self.T2, self.T3, self.T4] def is_policial(self): """ Devuelve un valor booleano para comprobar si la instancia del mismo modelo es policial """ return self.tipificacion == self.T1 class Calificaciones(models.Model): personal = models.ForeignKey(Personal, on_delete=models.PROTECT, null=True) periodo_desde = models.DateField(blank=True) … -
Dash app client-side callback not passing value to server-side callback
I'm working on a Dash app integrated with a Django template, and I'm encountering an issue where a client-side callback is not passing a value to a server-side callback. The value is correctly logged in the browser's console but appears as None on the server side when the server-side callback is triggered. **Minimal Code ** # template.html {% load plotly_dash %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> setTimeout(function() { function getSelectedLAName() { const selected_la_name_element = document.getElementById('selected-la-name'); if (selected_la_name_element) { const selected_la_name = selected_la_name_element.getAttribute('data-la-name'); console.log("Selected LA Name:", selected_la_name); return selected_la_name; } else { console.log("Element not found"); return null; } } getSelectedLAName(); // Call the function to test }, 500); // Delay in milliseconds </script> </head> <body> <h1>DASH APP Test</h1> <div id="selected-la-name" data-la-name="{{ selected_la.search_term }}"></div> {{ selected_la.search_term }} <div id="dash-container" style="width: 100%; height: 600px; border: 1px solid red;"> {% plotly_app name="dash_app" ratio=1 %} </div> </body> </html> # dash_app.py from django_plotly_dash import DjangoDash from dash import dcc, html from dash.dependencies import Input, Output from common.common_utils import * import plotly.graph_objects as go app = DjangoDash('dash_app') app.layout = html.Div([ html.Div(id='selected_la_name', style={'display': 'none'}), dcc.Dropdown( id='data-type', options=[ {'label': 'Number', 'value': 'number'}, {'label': 'Percentage', 'value': 'percentage'} ], value='number', style={'height': '30px', 'width': '50%', 'font-size': '16px'} ), … -
Submit the formset used in the below function
[17/Sep/2024 17:07:40] "GET /api/announcements/ HTTP/1.1" 200 299 POST data: <QueryDict: {'csrfmiddlewaretoken': ['JU9b2Ya9DZOVogoIXTSQ5BG4z8fvAmDnkkLReruwnkVKNx96gl52j6gbJJgOHblv', 'JU9b2Ya9DZOVogoIXTSQ5BG4z8fvAmDnkkLReruwnkVKNx96gl52j6gbJJgOHblv'], 'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-charge_type': ['4'], 'form-0-charge_period': ['yearly'], 'form-0-charge_amount_type': ['measurement_charge'], 'form-0-charge_amount': ['580'], 'form-0-tax_type': ['Rem iure minima nobi'], 'form-0-tax_percentage': ['9'], 'form-0-start_date': ['2024-11-15'], 'form-0-end_date': ['2024-12-05'], 'form-0-total_amount': ['632.20'], 'form-0-invoice_choices': ['selected_member'], 'form-0-full_name': ['5', '7', '8', '12'], 'form-0-description': ['Pariatur Dolore accusamus modi esse nihil sint non ducimus ipsum voluptatum molestiae omnis'], 'form-0-area': [''], 'form-0-maintenance_per_sq_feet': [''], 'form-0-flats': [''], 'form-0-building': [''], 'submit': ['Save']}> Form data: <QueryDict: {'csrfmiddlewaretoken': ['JU9b2Ya9DZOVogoIXTSQ5BG4z8fvAmDnkkLReruwnkVKNx96gl52j6gbJJgOHblv', 'JU9b2Ya9DZOVogoIXTSQ5BG4z8fvAmDnkkLReruwnkVKNx96gl52j6gbJJgOHblv'], 'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-charge_type': ['4'], 'form-0-charge_period': ['yearly'], 'form-0-charge_amount_type': ['measurement_charge'], 'form-0-charge_amount': ['580'], 'form-0-tax_type': ['Rem iure minima nobi'], 'form-0-tax_percentage': ['9'], 'form-0-start_date': ['2024-11-15'], 'form-0-end_date': ['2024-12-05'], 'form-0-total_amount': ['632.20'], 'form-0-invoice_choices': ['selected_member'], 'form-0-full_name': ['5', '7', '8', '12'], 'form-0-description': ['Pariatur Dolore accusamus modi esse nihil sint non ducimus ipsum voluptatum molestiae omnis'], 'form-0-area': [''], 'form-0-maintenance_per_sq_feet': [''], 'form-0-flats': [''], 'form-0-building': [''], 'submit': ['Save']}> Form errors: total_amountThis field is required. Formset data: <QueryDict: {'csrfmiddlewaretoken': ['JU9b2Ya9DZOVogoIXTSQ5BG4z8fvAmDnkkLReruwnkVKNx96gl52j6gbJJgOHblv', 'JU9b2Ya9DZOVogoIXTSQ5BG4z8fvAmDnkkLReruwnkVKNx96gl52j6gbJJgOHblv'], 'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-charge_type': ['4'], 'form-0-charge_period': ['yearly'], 'form-0-charge_amount_type': ['measurement_charge'], 'form-0-charge_amount': ['580'], 'form-0-tax_type': ['Rem iure minima nobi'], 'form-0-tax_percentage': ['9'], 'form-0-start_date': ['2024-11-15'], 'form-0-end_date': ['2024-12-05'], 'form-0-total_amount': ['632.20'], 'form-0-invoice_choices': ['selected_member'], 'form-0-full_name': ['5', '7', '8', '12'], 'form-0-description': ['Pariatur Dolore accusamus modi esse nihil sint non ducimus ipsum voluptatum molestiae … -
DRF Depth Only for Specified Fields for GET & POST
So, I have tried this Stack Overflow - Django REST Framework Depth Only For Specified Fields for specifying which field has depth, it's working, but when I want to do POST for insert new record, it can't because it's like django consider my field as required and set it to NULL. Here is my code... ../apps/models.py class GroupingTypes(models.Model): grouping_name = models.CharField(max_length=255, unique=True) description = models.TextField(null=True, blank=True) class Meta: db_table = 'grouping_types' class Templates(models.Model): id = models.UUIDField(primary_key=True, default=None, editable=False) ... name = models.CharField(max_length=255, default=None) grouping = models.ForeignKey(GroupingTypes, on_delete=models.CASCADE) file = models.FileField(upload_to="templates/") ... class Meta: db_table = 'templates' def delete(self, *args, **kwargs): if self.file and os.path.isfile(self.file.path): os.remove(self.file.path) super().delete(*args, **kwargs) ../apps/serializers.py class GroupingTypesSerializer(serializers.ModelSerializer): class Meta: model = GroupingTypes fields = "__all__" class TemplatesSerializer(serializers.ModelSerializer): # Extra fields that's not defined in models unix_timestamp_added = serializers.SerializerMethodField() datetime_added = serializers.SerializerMethodField() def get_unix_timestamp_added(self, obj: Templates): return int(obj.timestamp_added.timestamp()) def get_datetime_added(self, obj: Templates): return obj.timestamp_added.strftime("%Y-%m-%d %H:%M:%S") grouping = GroupingTypesSerializer(read_only=True) class Meta: model = Templates fields = "__all__" extra_kwargs = { 'file': {'write_only': True} } ../apps/views.py # `../utils/utils.py` def post(request: HttpRequest, Serializer: serializers.ModelSerializer): serializer = Serializer(data=request.data) if serializer.is_valid(): serializer.save() print(f"\033[92mPOST\033[0m") return Response( { "success": True, "msg": "added", "data": None, }, status=HTTP_201_CREATED ) print(f"\033[91mPOST\033[0m") return Response( { "success": False, "msg": serializer.errors, … -
Django collectstatic not working in production after changing tailwind.config.js
I recently change my local tailwind.config.js to add the breakpoint rules. In local, to apply change i do ./manage.py tailwind start (im using django-tailwind) and then collectstatic and the change is applied. But when i push it to production and do the exact step i can't see the changes happen after i restart the server. I have tried running in incognito mode, changing from Chrome to Firefox, hard refresh my browser, purge my cache in Cloudfare. But i still didnt see the changes. What can it be? is there an option to force django to refresh staticfiles? I thought restarting the server was enough. -
What is the best and the fastest way to switch from Django to Node.js? [closed]
I want to switch from Django(Python) to Node.js(JavaScript), and I'm planning to do this within 2 months at maximum for some reason. So, what is the best way to achieve to this goal? I see two ways to do this: 1-To start a course(video, book and etc..). 2- To start coding and learn the differences at the way. I have tested both of them in previous week. Just started coding with js, and writing some algorithms, and it was cool. Also started the Eloquent JS book; it is good also, but long. I prefer reading rather than watching, in general. What method of learning should I use? -
botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the PutObject operation: None upgrading to django-storages==1.14.4
I am encountering a ClientError: InvalidArgument when attempting to upload files to an S3 bucket using django-storages==1.14.4. This issue did not occur with django-storages==1.10, where the file upload process worked seamlessly. The error message is as follows: Internal Server Error: /chats/generate-document/ Traceback (most recent call last): File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\utils\decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\chat_app\views.py", line 235, in post user_chat.document.save(file_name, ContentFile(buffer.getvalue())) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\db\models\fields\files.py", line 99, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\django\core\files\storage\base.py", line 49, in save name = self._save(name, content) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\storages\backends\s3.py", line 564, in _save obj.upload_fileobj(content, ExtraArgs=params, Config=self.transfer_config) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\boto3\s3\inject.py", line 731, in object_upload_fileobj return self.meta.client.upload_fileobj( File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\boto3\s3\inject.py", line 642, in upload_fileobj return future.result() File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\s3transfer\futures.py", line 103, in result return self._coordinator.result() File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\s3transfer\futures.py", line 266, in result raise self._exception File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\s3transfer\tasks.py", line 139, in __call__ return self._execute_main(kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\s3transfer\tasks.py", line 162, in _execute_main return_value = self._main(**kwargs) File "C:\Users\tariq\OneDrive\Desktop\Important\aidocgen\venv\lib\site-packages\s3transfer\upload.py", line 764, in _main client.put_object(Bucket=bucket, Key=key, … -
'custom_filters' is not a registered tag library
I'm working on a Django project and encountering the following error when trying to load a custom template filter in my template: 'custom_filters' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz My folder structure: stream/ ├── templatetags/ └── __init__.py └── custom_filters.py ├── templates/ └── index.html My index.html: {% load custom_filters %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Newspaper results</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"> </head> <body> // HTML CODES </body> </html> my custom_filters.py: from django import template register = template.Library() @register.filter def get_item(dictionary, key): return dictionary.get(key) -
How to auto-play videos using IntersectionObserver in a Django project?
Problem Description: I'm working on a Django project where I want to auto-play videos when they are at least 70% visible in the viewport and pause them when they fall below 70%. I've written the JavaScript using IntersectionObserver, and the logic works well on its own. However, I'm facing some issues when integrating it into my Django template. What I Have Tried: I have a Video model in Django where each video file is stored. In the template, I loop through the videos and apply the IntersectionObserver logic for auto-play and pause. The videos load and display correctly, but the auto-play behavior isn't consistent. Here’s my setup: models.py: class Video(models.Model): vidid=ShortUUIDField(length=10,max_length=100,prefix="video",alphabet="abcdefgh") title = models.CharField(max_length=100) description = models.TextField(blank=True) video_file = models.FileField(upload_to='videos/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title views.py: def shorts_view(request,vidid): shorts1 = Video.objects.filter(vidid=vidid) shorts2 = Video.objects.all() context = { "shorts1":shorts1, "shorts2":shorts2, } return render(request,"videoshareing/shorts.html") shorts.html {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lazy Load Shorts</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"> <style> /* Global Styles */ body, html { margin: 0; padding: 0; background-color: #181818; color: #fff; font-family: Arial, sans-serif; height: 100%; overflow-y: scroll; } .shorts-container { display: flex; flex-direction: column; } .video-container { position: relative; height: … -
Custom error messages in Django Rest Framework
I have a serializer: class CompanyProfileCreateSerializer(serializers.ModelSerializer): class Meta: model = CompanyProfile exclude = ["id", "company"] class CompanyCreateSerializer(serializers.ModelSerializer): company_profile = CompanyProfileCreateSerializer(required=True) password = serializers.CharField(write_only=True) class Meta: model = Company fields = ["id", "email", "password", "company_profile"] extra_kwargs = { "password": {"write_only": True, "style": {"input_type": "password"}} } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Define custom error messages for all fields dynamically for field_name, field in self.fields.items(): field.error_messages.update({ "required": f"{field_name.replace('_', ' ').capitalize()} is required.", "null": f"{field_name.replace('_', ' ').capitalize()} cannot be null.", "invalid": f"Invalid value for {field_name.replace('_', ' ').capitalize()}." }) def create(self, validated_data): company_profile_data = validated_data.pop("company_profile") company = Company.objects.create(**validated_data, **company_profile_data) return company I added the __init__() method based on this answer to another question. But I am facing a problem. If I send the following request: { "email": "companytestregister1@gmail.com", "password": "password123", "company_profile": { "name": "Company Test Register1" } } the response I get is: { "field": "email", "detail": "user with this email already exists." } This is correct. The response is different from DRF's default error response because I am using custom exception handler. But the problem is that when I change the request to: { "password": "password123", "company_profile": { "name": "Company Test Register1" } } I still get the same error response. The … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE not working in Microsoft Edge
I am trying to log out users automatically when they close the browser or a tab. I have set: SESSION_EXPIRE_AT_BROWSER_CLOSE = True in my Django settings, and it works as expected in most browsers. However, it does not seem to work in Microsoft Edge. Is there a specific solution or workaround to make this functionality work in Edge? I also tried using beforeunload, but it logs out the user even when the browser is refreshed: $(document).ready(function() { $(window).on("beforeunload", function(e) { $.ajax({ url: "{% url 'logoutUser' %}", method: 'GET', }); }); }); -
Marking a Cookie as Partitioned in Django
This is my view: @ensure_csrf_cookie @require_http_methods(['GET']) def set_csrf_token(request): return JsonResponse({'message': 'Set CSRF cookie'}) I set this cookie in a Cross-Origin context so I also enable in my settings.py: CSRF_COOKIE_SAMESITE = "None" CSRF_COOKIE_SECURE = True However, my browser (FireFox and Chrome) both warn (require?) the use of Partitioned cookies; yet, Django appears to lack a setting for CSRF_COOKIE_PARTITIONED. So I ask what would be an elegant solution to setting my cookie as Partitioned? -
Django app under nginx and django gives a 502 sporadically on a large HTML page, other errors also
Before I did anything I would see a bad gateway on my deployed site or the error referenced here: Django/nginx/gunicorn giving this in deployment: GET https://.../ net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK) I changed a few things in nginx.conf and see less of the incomplete chunked error but still get the bad gateway. Viewing the nginx error.log I noticed errors that make no sense to me when I get the 502 bad gateway: 2024/09/16 12:34:24 [crit] 25088#0: *103 open() "/var/lib/nginx/tmp/proxy/4/01/0000000014" failed (13: Permission denied) while reading upstream, client: 10.75.0.152, server: 10.75.1.214, request: "GET /mainpage/nicfips/nicfipsguide/ HTTP/1.1", upstream: "http://unix:/run/apo_web.sock:/mainpage/nicfips/nicfipsguide/", host: "10.75.0.204:8080” I checked the folder where this referenced page exists and it is the same users as other links and and has what should be the correct chmod on it as well. As a test I took the HTML that is displayed on the page in question and it runs everytime so I know it is a timing issue of sorts, there is. just a REALLY long HTML page (I could break it up) but I am not sure why simple HTML is causing issues this day in age. The page does no database queries or anything. Guessing I need to edit a timing in … -
Django session creates new session key on every page refresh, causing duplicate carts
I am working on a Django app that uses user sessions to manage shopping carts. However, every time i refresh the page, a new session key is generated, which causes a new cart to be created. This results in multiple carts for the same user/session, which shouldn't happen. I'm try to understand why Django is creating a new session on every page refresh. On reload of /products multiple sessions are created in django backend [16/Sep/2024 17:11:31] "GET /api/products/ HTTP/1.1" 200 212 Session key: iedrvaus89536ly57pb242tnalwtx7vo [16/Sep/2024 17:11:31] "GET /api/carts/retrieve_cart/ HTTP/1.1" 200 107 [16/Sep/2024 17:11:31] "GET /api/products/ HTTP/1.1" 200 212 Session key: eipxdrmkf343fjtkchk7ads14ef1vccr [16/Sep/2024 17:11:31] "GET /api/carts/retrieve_cart/ HTTP/1.1" 200 107 If I click on add to cart I get two carts created: { "id": 77, "items": [ { "id": 66, "product": 1, "product_sku": "MNT-MST-MDL-HRV", "product_name": "Monthly Harvest Box", "product_price": 50.0, "quantity": 1 } ], "created_at": "2024-09-16T20:10:24.950541Z", "updated_at": "2024-09-16T20:10:24.950541Z" }, { "id": 78, "items": [], "created_at": "2024-09-16T20:10:25.006548Z", "updated_at": "2024-09-16T20:10:25.006548Z" } Here is ProductsPage.js import React, { useState, useEffect } from "react"; import './ProductsPage.css'; import Cart from './Cart'; import PictureGrid from "./PictureGrid"; const ProductsPage = () => { const [products, setProducts] = useState([]); const [cartItems, setCartItems] = useState([]); const [cart, setCart] = useState(null); // … -
xhtml2Pdf - converting a html to pdf consuming too much memory
I am trying to create a PDF using xhtml2pdf lib, but there is always a memory usage issue. There are around 4000 pages in this HTML.