Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to remove session id in logout?
I have a problem: when I do logout in Django I can still see a session id cookie in my browser and even after login I can acess an index page which is decorated with login_required. Please see the code below. @login_required(login_url='signin') def logout(request): auth.logout(request) return redirect('signin') @login_required(login_url='signin') def index(request): return render(request, 'index.html') I am quite frustrated and do not get what is misconfiured, chat gpt is suggesting some garbage(as ususal) Tried to remove session manually, tried to flush and so on - nothing works in chrome and safari -
Error Encountered: OrganizationFromTenantGuidNotFound
Error Encountered: OrganizationFromTenantGuidNotFound We are encountering an error related to Microsoft Graph API integration in our Django application. Specifically, the error message is: { "error": { "code": "OrganizationFromTenantGuidNotFound", "message": "The tenant for tenant guid 'e01c8511-af06-4cad-9b24-a63b9da7b0fc' does not exist.", "innerError": { "oAuthEventOperationId": "8b058e01-f527-4afe-9294-ee28aec98e19", "oAuthEventcV": "D3A3Bd+uExjl4MwXmDgIqw.1.1", "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant", "requestId": "fda9cb55-b436-4590-b3b3-3d847ee7e931", "date": "2024-09-16T18:42:41" } } } This happens when trying to authenticate using Azure AD and fetch emails via Microsoft Graph API. The decoded token shows a valid tenant_id, client_id, and permissions, but we suspect there might be an issue with the tenant configuration or app registration on Azure. At the moment, using the token, I can get a list of all users. However, when I go to the information on a specific user, an error occurs. However, on the application side, no errors are displayed. My main task is to configure the functionality of sending messages from my application, so that messages sent to the user's address are visible in the application (also when sending a message to a user). https://graph.microsoft.com/v1.0/users/ { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users", "value": [ { "businessPhones": [], "displayName": "Demo Mail", "givenName": null, "jobTitle": null, "mail": "demotest@tester.com, "mobilePhone": null, "officeLocation": null, "preferredLanguage": null, "surname": null, "userPrincipalName": "---", "id": "d028f0d4-0838-4925-8eeb-5f6651b6cfb1" }, ] … -
Setting up React with DRF?
Currently, I'm following some lessons on my course and building a social media website project for assessment in future. I am currently stuck with getting my React App built within a Django Rest Framework App to display even the default React page when hosting Live Server, I will link my repo below if it helps I feel like I have gone in circles now as I'm not fully clued in on a full stack project yet (hence trying to get it together). Very much appreciate if anyone could take a look and help me out. I am a bit of a noob so may be obvious and I'm missing something entirely. https://github.com/conor-timmis/Better-You So far I've been dabbling with the Views & urls of the main app, but not sure where to go from there. Lessons have not really explained this so much, only creating the apps separately then linking them together, but mention building within one repo instead with a full app but I am building from scratch so that's not really an option. (I have tried building my app and putting them into static as I read that in another thread but didn't have any luck with that). -
How do you serve a generated file using Django?
For example, the Django sitemap middleware, generates a sitemap and then serves it from localhost:8000/sitemap.xml. If I were to serve a file in a similar manner, following the same url structure, how would I do this? I have a view and urls file: class FileView(View): def get(self, request): return HttpResponse(open('myfile.xml').read(), content_type='text/xml') # urls.py urlpatterns = [ path( '/myfile.xml', PageView.as_view() ) ] This will fail to render with a 404, and will constantly append a / to the url, so it looks for localhost:8000/myfile.xml/. However, if I change my urlpatterns to use '/myfile', without the file extension, it renders the file correctly. Is there a correct way to serve this using the file exentsion without resorting to dropping it into static files? -
Not able to serve React build files with Django
I have been trying to serve my dist files of React frontend app to my Django project. However, the browser keeps refusing to serve static files and throws the error described below: > Refused to apply style from 'http://localhost:8000/static/my-react-app/assets/index-CgY6hLMH.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. > Refused to apply style from 'http://localhost:8000/static/my-react-app/assets/index-CgY6hLMH.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. > index-LlsxC_Wu.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. Here's how my Django repository looks: enter image description here All my CSS and JS static files are inside assets while index.html is the template I want to serve. My settings.py file looks like this: enter image description here I already tried rebuilding the dist files and copying them to the static directory and made changes to static paths as well but all in vain.