Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Troubles AJAX Integration with Django
When I save products from ajax to db, it always redirects me to failed page and saying 500 server error views.py from cart.cart import Cart from django.http import JsonResponse from django.shortcuts import render from .models import Order, OrderItem, ShippingAddress # Create your views here. def checkout(request): if request.user.is_authenticated: try: shipping_address = ShippingAddress.objects.get(user=request.user.id) context = {'shipping': shipping_address} return render(request, 'payment/checkout.html', context=context) except: return render(request, 'payment/checkout.html') else: return render(request, 'payment/checkout.html') def complete_order(request): if request.POST.get('action') == 'post': name = request.POST.get('name') email = request.POST.get('email') address1 = request.POST.get('address1') address2 = request.POST.get('address2') city = request.POST.get('city') state = request.POST.get('state') zipcode = request.POST.get('zipcode') print(name) shipping_address = (address1 + "\n" + address2 + "\n" + city + "\n" + state + "\n" + zipcode ) cart = Cart(request) total_cost = cart.get_total() if request.user.is_authenticated: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost, user=request.user) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price'], user=request.user) else: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price']) order_success = True response = JsonResponse({'success':order_success}) return response urls.py from django.urls import path from . import views urlpatterns = [ path('checkout', views.checkout, name='checkout'), path('complete-order', views.complete_order, name='complete-order'), path('payment-success', views.payment_success, name='payment-success'), path('payment-failed', views.payment_failed, name='payment-failed'), ] checkout.html {% include "store/base.html" %} {% … -
"Waiting list" or delay when sending emails with Django and the win32 library
I have just discovered something in the provided code, and I would like to explain it to you. During my tests with the email sending using this code, everything seemed to work correctly, but a specific issue arose. Let's say I have three emails to send: email 1, email 2, and email 3. When I send email 1, the console returns a 200 OK status, but the email doesn't reach my inbox. Then, when I proceed to send email 2, the console again returns a 200 OK status, and although a new email appears in my inbox, it turns out to be email 1. After waiting several minutes without receiving any updates or new emails, I proceed to send email 3. At this point, the console once again shows a 200 OK status, and, surprisingly, I receive a new email in my inbox, but now it is email 2. ` class ApiSendMailCreateNewReporter(APIView): def get(self, request, id_headerRequest): try: # Obtener el objeto HeaderRequest o devolver un error 404 si no existe header_request = get_object_or_404(HeaderRequest, id=id_headerRequest) # Serializar el objeto HeaderRequest serializer_header_request = HeaderRequestSerializer(header_request) usuario_id = serializer_header_request.data['id_user_id'] require_date = serializer_header_request.data['require_date'] customer = serializer_header_request.data['customer'] # Obtener la instancia de Engineers con role='admin' o … -
Why Is a migration file created (over and over) when i run makemigrations
Am facing a somehow funny issue...every time i migrate,i get this description Your models in app(s): 'organization_app' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. so i follow what django says and i makemigrations,this migration file is created # Generated by Django 4.2.3 on 2024-02-07 20:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("organization_app", "0002_alter_penaltymodel_tenant_penalty_choice"), ] operations = [ migrations.AlterField( model_name="penaltymodel", name="tenant_penalty_choice", field=models.CharField( choices=[("PERCENT", "Percent"), ("AMOUNT", "Amount")], default="AMOUNT", max_length=20, ), ), ] when i migrate,i get the same description i stated earlier 'manage.py makemigrations' and when i migrate, the same migration file is created over and over..is this a #bug -
error to show week name django-jalali-date and django
I have developed a website using Django for appointment scheduling purposes. This website utilizes Persian dates and the Jalali date library from Django Jalali. However, I am encountering an issue where on my local system, it displays correctly, showing Persian month names, but when deployed on the server, it displays month names in English and day names in English as well.Could someone provide guidance on resolving this matter? See these pictures: on server : img 1 on site - img 2 on site on my system: img 1 on site - img 2 on site However, I am encountering an issue where on my local system, it displays correctly, showing Persian month names, but when deployed on the server, it displays month names in English and day names in English as well. -
how to solve JSONDecodeError
i made a edit function to edit the post which works fine i can see that in the console when the post button is clicked and when i refresh page the value is being updated but i am getting this error for some reason and i am not able to solve it. def edit_post(request, post_id): if request.method == 'POST': data = json.loads(request.body) post = Post.objects.get(pk=post_id) post.content = data['content'] post.save() return JsonResponse({"message": "Post edited successfully.", "data": data['content']}) getCookie = (name) => { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length == 2) return parts.pop().split(';').shift(); } update = (id) => { const updatedValue = document.getElementById(`textarea_${id}`).value fetch(`/edit_post/${id}`, { method: "POST", headers: { "Content-type": "application/json", "X-CSRFToken": getCookie("csrftoken") }, body: JSON.stringify({ content: updatedValue }) }) .then(response => response.json()) .then(result => console.log(result) ) } JSONDecodeError at /edit_post/18 Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://127.0.0.1:8000/edit_post/18 Django Version: 5.0 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Program Files\Python312\Lib\json\decoder.py, line 355, in raw_decode Raised during: network.views.edit_post Python Executable: C:\Program Files\Python312\python.exe Python Version: 3.12.0 -
The problem of using the Arabic language in django links
I am programming a website in Django I want to put the Arabic language in my link, but when I make the link in Arabic and when I choose it, it takes me to the page page not found Note: This only happens on the hosting server, meaning it does not happen on localhost urls.py from django.urls import path, re_path from . import views urlpatterns = [ # pages path('',views.index,name='index'), path('الصفحة/',views.listArticle,name='listArticle'), path('TravelTips/',views.TravelTips,name='TravelTips'), # view article path('الصفحة/<str:slug_url>/', views.view_article, name='Page_Article'), path('TravelTips/<str:slug_url>/',views.view_article,name='Page_Article'), ,] I expected that the problem was in the slug, but it turned out that Django in general did not accept Arabic letters -
CDN imports for PDF.js viewer.html in Django templates
I am trying to add the PDF.js viewer as it appears in the official demo in an HTML iframe of my Django template. I do not want include any of the assets of PDF.js in my repository and I want all my script and stylesheet HTML tags to refer to a CDN resource. Since the documentation contains a note that users of the library should not just copy/paste the web/viewer.html, I have created my own modified version named custom_viewer.html, which includes a subset of the features of the official demo. The prebuilt version of the library includes the following four tags in the demo web/viewer.html: <link rel="resource" type="application/l10n" href="locale/locale.json"> <script src="../build/pdf.mjs" type="module"></script> <link rel="stylesheet" href="viewer.css"> <script src="viewer.mjs" type="module"></script> My question is what are the corresponding CDN links to get this working without downloading the PDF.js library on the server? I have managed to replace the pdf.mjs file reference with a CDN link. More specifically, I have verified that when I copy the prebuilt PDF.js (version 4.0.379) in my static folder and I modify the paths as follows: {% load static %} <link rel="resource" type="application/l10n" href="{% static 'my-django-app/pdfjs-4.0.379-dist/web/locale/locale.json' %}"> <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@4.0.379/build/pdf.mjs" type="module"></script> <link rel="stylesheet" href="{% static 'my-django-app/pdfjs-4.0.379/web/viewer.css' %}"> <script src="{% static … -
Django, Subquery, more than one row returned by a subquery used as an expression
Here is my model structure class ContentFlag(models.Model): user = models.ForeignKey( User, verbose_name="user", related_name="object_flags", on_delete=models.CASCADE, ) flag = models.CharField(max_length=30, db_index=True) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Article(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("owner"), null=True, blank=True, editable=True, on_delete=models.SET_NULL, related_name="owned_pages", ) flags = GenericRelation(ContentFlag, related_query_name="%(class)s_flags") title = models.CharField(max_length=255) class User(index.Indexed, AbstractUser): email = EmailField(verbose_name="email", unique=True, null=True, blank=True) name = models.CharField( blank=True, max_length=100, ) flags = GenericRelation(to="core.ContentFlag") I need to calculate User rating based on Flags number. Here is what I do for that subquery_plus = ContentFlag.objects.filter( Q(article_flags__owner_id=OuterRef("id")), flag=LIKEDIT_FLAG, ).values("id") top_users = ( User.objects.annotate( rating_plus=Count(Subquery(subquery_plus)), ).order_by("-rating_plus") ) But I got an error django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression How can I fix that? -
Django background tasks - problem with process_tasks
I have a strange case and don't know how to solve it. Namely I have installed Django background tasks, made a migration and added to installed aps. I run python manage.py process_tasks in the terminal, open a second terminal and runserver. Everything is ok. In the admin panel I see: Completed Tasks and Tasks. The first terminal listens all the time for the execution of the task and when I let it go it works perfectly. However, if I enter Completed Tasks or Tasks in Admin while the task is running, the first terminal immediately stops listening and goes back to waiting for the prompt. Anyone perhaps know what this is all about? -
Django Rest Framework New User Registration with Admin activation
in the old Django times I was able to set the is_activated hidden field per registration of the user data to let the new user to registrate but not able tro login. An admin needed to activate the account - perfect. With the django rest framework I can't find a possibility to do the same action. Can I get a hind please .... thank you very much. Other maybe stupid question of this - how can I prevent the user from login without validation ( not Email validation ) Thanks a lot Greetings RR I tried successfully to add a user with all the methods I found online but always is_active was true Also it looked that the framework is always taking this field as true because its an admin feature to deactivate accounts - but this is the same I like to do. -
Django and extract IPTC from images
Maybe a stupid question, but how can I extract information from the image, such as description, headline and keywords using Django & Pillow? I have this now, but it dont work at all.. Can you help me to fix this or help me with a solution? I can see the IPTC information in photoshop and other software, but i cant see it if upload the images in my django project. def extract_iptc_data(image_file): print("Extracting IPTC data...") # Add this print statement # Open the image file img = PilImage.open(image_file) # Initialize title, description, and keywords title = None description = None keywords = [] # Extract XMP metadata xmp_data = img.info.get("xmp", b"") print("XMP Data:", xmp_data) # Print XMP metadata for debugging if xmp_data: # Parse XMP metadata xmp_tree = ET.fromstring(xmp_data) # Find headline (title), keywords, and description for elem in xmp_tree.iter(): if elem.tag.endswith("Headline"): title = elem.text elif elem.tag.endswith("Keywords"): keywords.extend(elem.text.split(",")) elif elem.tag.endswith("Description"): description = elem.text return title, description, keywords -
how to solve JSONDecodeError
def edit_post(request, post_id): if request.method == 'POST':` data = json.loads(request.body) post = Post.objects.get(pk=post_id) post.content = data['content'] post.save() return JsonResponse({"message": "Post edited successfully.", "data": data['content']}) getCookie = (name) => { const value = ; ${document.cookie}; const parts = value.split(; ${name}=); if (parts.length == 2) return parts.pop().split(';').shift(); } update = (id) => { const updatedValue = document.getElementById(`textarea_${id}`).value fetch(`/edit_post/${id}`, { method: "POST", headers: { "Content-type": "application/json", "X-CSRFToken": getCookie("csrftoken") }, body: JSON.stringify({ content: updatedValue }) }) .then(response => response.json()) .then(result => console.log(result) ) } path("edit_post/<int:post_id>", views.edit_post, name="edit_post"), The function is working fine because the post are updated when reloaded but when i click on post i am thrown to this error. JSONDecodeError at /edit_post/18 Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: ``http://127.0.0.1:8000/edit_post/18 Django Version: 5.0 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Program Files\Python312\Lib\json\decoder.py, line 355, in raw_decode Raised during: network.views.edit_post Python Executable: C:\Program Files\Python312\python.exe Python Version: 3.12.0 // html {% if user.is_authenticated %} {% if user == post.user %} <a class="editButton btn btn-link"> Edit </a> <div class="editModal modal"> <div class="modal-content"> <!-- Add a close button --> <span class="ecloseButton" style="position: absolute; right: 20px; top: -8px;left: 530px; font-size: `your text`20px; cursor: … -
KeyError while using CreateView on Django
when im trying to create an objet 'Comprobante' throws me the error: KeyError at /caja_chica/comprobantes/crear/ 'comprobante' Request Method: POST Request URL: http://127.0.0.1:8000/caja_chica/comprobantes/crear/ Django Version: 3.2.5 Exception Type: KeyError Exception Value: 'comprobante' here is my model Comprobante: class Comprobante(models.Model): TIPO_A = 1 TIPO_B = 2 TIPO_C = 3 TIPO_T = 4 TIPO_X = 5 TIPO_CHOICES = ( (TIPO_A, 'A'), (TIPO_B, 'B'), (TIPO_C, 'C'), (TIPO_T, 'T'), (TIPO_X, 'X'), ) caja_chica = models.ForeignKey(CajaChica, on_delete=models.PROTECT) lote = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='lote_comprobantes') numero = models.CharField(max_length=13) tipo = models.PositiveSmallIntegerField(choices=TIPO_CHOICES, default=TIPO_T) ente = models.ForeignKey(Ente, on_delete=models.PROTECT) fecha = models.DateField() partida_presupuestaria = models.ForeignKey(PartidaPresupuestaria, on_delete=models.PROTECT) detalle = models.CharField(max_length=100) importe = models.DecimalField(max_digits=7, decimal_places=2) history = HistoricalRecords() def __str__(self): return self.numero #def save(self, *args, **kwargs): # super(Comprobante, self).save(*args, **kwargs) # self.caja_chica.disponible -= self.importe # self.caja_chica.save() def get_absolute_url(self): """ Devuelve la url para acceder a una instancia particular de Comprobante. """ return reverse('caja_chica:comprobante_update', args=[str(self.id)]) here is my form: class ComprobanteForm(forms.ModelForm): class Meta: model = Comprobante fields = ('__all__') my view using CreateView: class ComprobanteCreate(SuccessMessageMixin, CreateView): model = Comprobante fields = '__all__' success_url = reverse_lazy('caja_chica:comprobante_list') success_message = "%(comprobante)s fue creado exitosamente" and my template of comprobante_form: {% extends "caja_chica/base.html" %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'caja_chica:inicio' %}">Inicio</a> > <a … -
Getting ReplicaSetNoPrimary error for M0 cluster when using Django with MongoEngine
I am using django with mongoengine. I am writing the following in the settings.py file: from mongoengine import connect URI = 'mongodb+srv://myusername:mypassword@cluster0.5apjp.mongodb.net/django?retryWrites=true&w=majority&ssl=false' connect(host=URI) After that, I have a model as follows: from mongoengine import Document, StringField class User(Document): first_name = StringField(max_length=50) last_name = StringField(max_length=50) meta = { 'collection': 'users' } I have a view as follows: def adduser(request): userDict = json.loads(request.body) newUser = User(first_name=userDict['firstName'],last_name=userDict['lastName']) newUser.save() return HttpResponse('user added') When this view function is called, I get an error as follows: ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),cluster0-shard-00-01.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),cluster0-shard-00-00.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 65c3bdc13c9136a1191890e1, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.5apjp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('cluster0-shard-00-01.5apjp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('cluster0-shard-00-02.5apjp.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.5apjp.mongodb.net:27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]> [07/Feb/2024 23:02:38] "POST /user/adduser HTTP/1.1" 500 115166 I am using a mongodb free M0 cluster with database named as 'django' and collection named as 'users'. If I use a non-SRV URI string like localhost:27017, it … -
How to run a one-off ECS task in CodePipeline using Terraform?
I'm trying to set up deployment for a Django web app using Code Build, Code Pipeline and Terraform but I can't figure out how to start a one off task in the pipeline to run the migrations. I've found this code snipper for the stage but it seems TaskDefinition is not a valid name in the config for aws_codepipeline. stage { name = "RunMigrations" action { name = "RunMigrationsAction" category = "Deploy" owner = "AWS" provider = "ECS" version = "1" input_artifacts = ["BuildOutput"] configuration = { ClusterName = var.ecs_cluster_name TaskDefinition = "django-migration-task" } } } resource "aws_ecs_task_definition" "django_migration" { family = "django-migration-task" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] execution_role_arn = aws_iam_role.ecs-task-execution-role.arn cpu = 256 memory = 512 container_definitions = jsonencode([ { name = "django-migration-container" image = aws_ecr_repository.ecr_repository.repository_url command = ["python", "manage.py", "migrate"] logConfiguration = { logDriver = "awslogs" options = { awslogs-group = "/ecs/logs" awslogs-region = var.aws_region awslogs-stream-prefix = "ecs" } } portMappings = [ { containerPort = 8000 } ] } ]) } -
"Given token not valid for any token type" error in django when i send header with Authorization: None
When I send request to my backend i got error: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } I have this in views.py class ProblemViewSet(viewsets.ModelViewSet): queryset = models.Problem.objects.all() serializer_class = serializers.ProblemSerializer permission_classes = [] def retrieve(self, request, *args, **kwargs): print(request.META) instance = self.get_object() user = request.user if user is not None and not user.is_anonymous: interaction, created = models.InteractionUserProblem.objects.get_or_create(user=user, problem=instance) if created: interaction.is_viewed = True interaction.save() serializer = self.get_serializer(instance) return Response(serializer.data) and this in settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ["rest_framework_simplejwt.authentication.JWTAuthentication"], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], "TEST_REQUEST_DEFAULT_FORMAT": "json", 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } from frontend come header with Authorization: Bearer none if user is not authenticated. I know solution to add authentication_classes = [], but i need authentication, to recognize user if he is authenticated. So how can i fix it, maybe i need to add some middleware? I tried to add authentication_classes = [], but this is not solution for me. I need to catch Authorization: Bearer none somehow and process it. -
Restrict output of fields in Django admin according to previous selection
I have this model.py: class Funder(models.Model): name = models.CharField(max_length=200) scheme = models.ManyToManyField('Scheme', blank=True) class Scheme(models.Model): name = models.CharField(max_length=200)) class Project(models.Model): title = models.CharField(max_length=200) funder = models.ManyToManyField(Funder) scheme = models.ForeignKey(Scheme, on_delete=models.SET_NULL) A funder can have 0, 1, or many schemes attached to it. I'd like to limit the choice of schemes that can be selected from the admin form for project to only the schemes that belong to a specific funder. Is that possible? Example: in 'new project', people select funder1, and only see scheme1, scheme3, scheme5 in the drop-down for scheme, because scheme2 and scheme4 are associated to funder2. Is this something that can be obtained with a QuerySet? My ModelAdmin: from import_export.admin import ImportExportModelAdmin class FunderAdmin(ImportExportModelAdmin): search_fields = ['name',] autocomplete_fields = ['scheme'] list_display = ("name",) -
How to implement HMTX with Django Class Based Views
I am trying to understand how to utilise htmx with Django Class Based Views. To provide some context, here is a reflection of the scenario in which I want to implement django class based views and htmx together: I have an initial view, which renders the main template and initial context. As part of this initial context, I am including a date form. I want to use htmx to post the data from this form to an APIView (let’s call it APIView1). I would like APIView1 to ingest the data which is posted to it via htmx, run a function on it, and then return data back as context, while rendering a partial template (let’s call it PartialTemplate1) which utilises that context. So from what I understand, I can do this within a get() function; so it may look a little like this: views.py Class InitialView(View): template_name = “initial_template.html” form_class = date_form def get(self, request, *args, **kwargs): … date_form=self.form_class() context = { 'date_form': date_form } return render(request, template_name, context) Class APIView1(APIView): template_name = “PartialTemplate1.html” def get(self, request, *args, **kwargs): date = request.POST.get(‘date’) timeslots = function(date) context = { ‘timeslots’: timeslots } return render(request, template_name, context). initial_template.html: <form hx-post='{% url "appname:apiview1_url" … -
Warning: Received `true` for a non-boolean attribute `crossOrigin` when using NextJS/React + Django Rest Framework
I've been receiving this warning but have little idea where it may originating from or how to solve it. It appeared seemingly out of nowhere. I went back a few commits and the warning still appeared, although I'm certain it was not present when I was initially working on those commits. I have some suspicions it may be related to CORS, or to my snake_case to camelCase converting middleware. I am using a NextJS/React frontend and a Django Rest Framework backend. Error message: app-index.js:35 Warning: Received `true` for a non-boolean attribute `crossOrigin`. If you want to write it to the DOM, pass a string instead: crossOrigin="true" or crossOrigin={value.toString()}. at link at head at html at RedirectErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9) at RedirectBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/redirect-boundary.js:81:11) at NotFoundErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:76:9) at NotFoundBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found-boundary.js:84:11) at DevRootNotFoundBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/dev-root-not-found-boundary.js:33:11) at ReactDevOverlay (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:84:9) at HotReload (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:307:11) at Router (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:181:11) at ErrorBoundaryHandler (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:114:9) at ErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:161:11) at AppRouter (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:536:13) at ServerRoot (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:129:11) at RSCComponent at Root (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:145:11) Django settings.py: CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:3000", "https://localhost:3000", ] INSTALLED_APPS = [ "core", "rest_framework", "corsheaders", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "compressor", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "djangorestframework_camel_case.middleware.CamelCaseMiddleWare", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] React Frontend API calls: import * as constants from '../constants/endpoints' … -
Django fields not saving
I want to receive a file from the client and perform some processing on the image in the corresponding model class before it is saved in the database. However, since the file is not saved until the end of the save() method, the directory where the file is stored is not created and I get the error FileNotFoundError: [Errno 2] No such file or directory: 'media/upload/vertical_image.jpg'. I'm actually looking for a way to do all the processing in the save method this is my Media model: title = models.CharField(max_length=255, null=True, blank=True) file = models.FileField(upload_to="upload/") filename = models.CharField(max_length=255, null=True, blank=True) mime_type = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.JSONField(null=True, blank=True) size = models.FloatField(null=True, blank=True) url = models.CharField(max_length=300, null=True, blank=True) thumbhash = models.CharField(max_length=255, blank=True, null=True) is_public = models.BooleanField(blank=True, null=True) def save(self, *args, **kwargs): sizes = [(150, 150), (256, 256)] media_path = f"media/upload/{self.filename}" image = Image.open(media_path) mime_type = image.get_format_mimetype() format = mime_type.split("/")[1] if not os.path.exists("media/cache"): os.makedirs("media/cache") thumbnail = {} for i, size in enumerate(sizes): resized_image = image.resize(size) index = "small" if i == 0 else "medium" file_path = os.path.join( "media", "cache", f"{self.id}-resized-{self.filename}-{index}.{format}", ) resized_image.save(file_path, format=format) thumbnail["*".join(str(i) for i in size)] = file_path self.mime_type = mime_type self.size = os.path.getsize(media_path) self.thumbnail = thumbnail self.url = f"http://127.0.0.1:8000/media/upload/{self.filename}" … -
How to have multiple email backends in Django?
I would like to have both SMTP backend and console backend, so that I can send an email via SMTP while also printing the generated email to console. In my settings.py I would like to have something like this: EMAIL_BACKEND = ["django.core.mail.backends.smtp.EmailBackend", "django.core.mail.backends.console.EmailBackend"] -
how to change the django connection string with postgres in each request in order to have a record of changes
Good afternoon, I have a trigger in my database that records every change, inclusion or deletion in the tables, but instead of using the user ID connected to Postgres, I would like to pass the user ID of my application, as it is an application SASS, I will have "a user" for the database, and "n" for the application. Is there any way to pass this user to my connection? where can I retrieve it in the trigger by executing select * from pg_stat_activity? I know the solution may seem inelegant, but it provides a lot of reliability when auditing data in the database I'm using: Django 4.2 DRF 3.14.0 Postgres 16.1 I tried to change the DATABASE parameters of settings.py, before the connection and I even managed to change the application_name, but when two users execute their requests "at the same time", there is a conflict and the two connections have the same value in the application_name. -
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'book.CustomUser' that has not been installed raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'book.CustomUser' that has not been installed -
Django rest social auth and simple-jwt: NoReverseMatch at /api/login/social/jwt-pair/
I was following the documentation on drf social auth https://github.com/st4lk/django-rest-social-auth/tree/master I've encountered an issue while working with Django-Rest-Social-Auth and Simple-JWT. The error message is as follows: NoReverseMatch at /api/login/social/jwt-pair/facebook/ 'http' is not a registered namespace I've registered my path in the root urls.py (located in the config folder) as follows: path("api/login/", include("rest_social_auth.urls_jwt_pair")) Despite referring to the documentation, I'm unable to resolve this error. If anyone has encountered a similar issue or has insights into what might be causing this problem. Could someone kindly assist? -
Issues with Database Router Configuration in Django for Handling Multiple Databases
I am working on a Django application that utilizes two databases: Primary Database: This is set as the default database and is primarily used for read-only operations, such as querying analytics data. It does not handle authentication or any write operations. Secondary Database (sqlserver_db): This database is used for write operations, including migrations and authentication-related tasks. I am encountering difficulties in configuring the database router in my settings.py to properly direct read and write operations to the appropriate database. Below is my current setup: I am struggling to set the database router in my settings.py file below is what I have done in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'AAAA', 'USER': 'AAAA', 'PASSWORD': 'AAAA', 'HOST': 'AAAA', 'PORT': 'AAAA', 'OPTIONS': { 'threaded': True, }, }, 'sqlserver_db': { 'ENGINE': 'mssql', 'NAME': 'AAAA', 'USER': 'AAAA', 'PASSWORD': 'AAAAA', 'HOST': 'AAAAA', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } DATABASE_ROUTERS = ['MyApp.routers.AuthRouter'] and there in routers.py : class AuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {"auth", "contenttypes"} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ …