Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different session objects in the same session Django
I have a problem with django sessions. This is the first time I've come across this. When accessing request.session in two different views, I get two different SessionStore objects, so I don't get variables from it. I'm writing a variable in one view and I want to get it in another view, that's all I need. All sessions are cleared, cookies are cleared and still the same result. I tried to make a delay of 2 seconds before going to another view in order to have time to write to the db, it does not help. I only use the debug server and the default settings, in middleware the standard settings, I do not use the caches server. I use Django 5.0.7. Has anyone encountered this? enter image description here where do I write the variable class SignYandexView(View): def get(self, request): client = oauth2.Client(client_id=os.getenv("YANDEX_CLIENT_ID")) code_verifier = client.create_code_verifier(length=50) code_challenge = client.create_code_challenge(code_verifier=code_verifier, code_challenge_method="S256") request.session["code_verifier"] = code_verifier print(request.session) return redirect("....") where do I want to get class CallbackYandexView(View): def get(self, request): code = request.GET.get('code') print(request.session) code_verifier = request.session["code_verifier"] -
Django: Error sending email: (530, b'5.7.0 Authentication Required
I am working on a Django project and get the problem with sending email. This is my code in views.py class ForgotPasswordView(APIView): def get(self, request): return render(request, 'login/forgot_password.html') def post(self, request): email = request.data.get('email') if not email: return Response({"message": "", "error": " Email required." }, status=status.HTTP_400_BAD_REQUEST) try: user = User.objects.get(email=email) except User.DoesNotExist: return Response({"message": "", "error": "Email not found." }, status=status.HTTP_400_BAD_REQUEST) #Tao token token = default_token_generator.make_token(user) #Tao link reset_password uid = urlsafe_base64_encode(force_bytes(user.pk)) reset_url = request.build_absolute_uri( reverse('reset_password', kwargs={'uidb64': uid, 'token': token}) ) #Gui email send_mail( 'Reset Password', f'Click following link to reset your password: {reset_url}', os.environ.get('EMAIL_HOST_USER'), [email], #Email nhận fail_silently=False ) return Response({"message": "Mail đặt lại mật khẩu đã được gửi", "error": "" }, status=status.HTTP_200_OK) But the problem is here smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. For more information, go to\n5.7.0 https://support.google.com/mail/?p=WantAuthError d9443c01a7336-1fed7fbf285sm27418485ad.267 - gsmtp', 'sender@gmail.com') I thinh my email setting have some problems so I have a test in tests.py and I work totally fine. from dotenv import load_dotenv load_dotenv() from django.conf import settings from django.core.mail import send_mail import os import sys import django project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "system.settings") django.setup() try: send_mail( 'Test Subject', 'Test message body', os.environ.get('EMAIL_HOST_USER'), ['reciever@outlook.com'], fail_silently=False, ) print("Test email sent successfully") except Exception as e: print(f"Error … -
How to send 401 response with custom login_required decorator after django session expire?
I have a custom login_required decorator which looks like this - def login_required(function): """ Ensure that user is logged in """ def wrap(request, *args, **kwargs): if request.user.is_anonymous: message = { "status": "error", "message": "user login error", "data": "user is not logged in", } return HttpResponse( content=json.dumps(message).encode("utf-8"), status=401, headers=None, content_type="application/json", ) return function(request, *args, **kwargs) return wrap When my request comes in and django session has expired, I see my custom message in the response. However, the status of response code is 302 redirect with the next?=path in url. When I have the network tab open in browser inspect, I sometimes see Cors error but this is not constant. I have configured SESSION_TIMEOUT_REDIRECT, LOGOUT_REDIRECT, LOGIN in settings. Below is what my middleware looks like - MIDDLEWARE = [ "csp.middleware.CSPMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django_session_timeout.middleware.SessionTimeoutMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "core.middleware.admin_pages_middleware.AdminPagesMiddleware", ] I want my response to be 401 and not 302. Could you please let me know what am I missing? Thanks! Tech stack - Python 3.12, Django 5.0 I have tried configuring different django settings. I see the custom error message but not the 401 response. -
KeyError at /verify/ 'order_id'
I have a problem on my store site, when I want to confirm my order, when I click on confirmation on the payment page, it gives this error instead. the error Internal Server Error: /verify/ Traceback (most recent call last): File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.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\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\cart\views.py", line 124, in get order_id = request.session['order_id'] ~~~~~~~~~~~~~~~^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\contrib\sessions\backends\base.py", line 53, in __getitem__ return self._session[key] ~~~~~~~~~~~~~^^^^^ KeyError: 'order_id' [26/Jul/2024 09:38:14] "GET /verify/?Authority=000000000000000000000000000001476833&Status=OK HTTP/1.1" 500 83027 Not Found: /favicon.ico [26/Jul/2024 09:38:14] "GET /favicon.ico HTTP/1.1" 404 5053 I asked some people what should I do to solve my problem and they told me that I didn't set the order_id in the session. view.py from django.shortcuts import render, redirect, get_object_or_404 from account.models import Address from .models import Order, OrderItem, DiscountCode from django.http import JsonResponse from django.http import HttpResponse from product.models import Product from django.conf import settings from django.views import View from .cart_module import Cart import requests import json class CartView(View): def get(self, request): cart = Cart(request) … -
django OAuth Toolkit not getting redirect URI
I am using Django OAuth toolkit and using the following code for OAuth implementation Application = get_application_model() def oauth_login(request): app = Application.objects.get(name="App") #redirect_uri = request.GET.get("redirect_uri", "http://test.com:8000/callback") #redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/malicious_redirect.html") redirect_uri = request.POST.get("redirect_uri", "http://test.com:8002/malicious_redirect.html") authorization_url = ( f"http://test.com:8000/o/authorize/?client_id={app.client_id}&response_type=code&redirect_uri={redirect_uri}" ) return redirect(authorization_url) def oauth_callback(request): code = request.GET.get("code") if not code: return JsonResponse({'error': 'missing_code', 'details': 'Missing code parameter.'}, status=400) token_url = "http://test.com:8000/o/token/" client_id = Application.objects.get(name="App").client_id client_secret = Application.objects.get(name="App").client_secret #redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/callback") redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/unique_redirect.html") data = { "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri, "client_id": client_id, "client_secret": client_secret, } headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': f'Basic {base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()}', } response = requests.post(token_url, data=data, headers=headers) tokens = response.json() print(tokens) if response.status_code != 200: return JsonResponse({'error': 'token_exchange_failed', 'details': tokens}, status=response.status_code) request.session['access_token'] = tokens['access_token'] request.session['refresh_token'] = tokens['refresh_token'] return JsonResponse(tokens) #return redirect('profile') The problem is that if I am logged into the OAuth 2.0 admin panel with superuser credentials, the above code works fine and redirects to the provided URL. Otherwise it doesn't work and uses the LOGIN_REDIRECT_URL = '/profile/' from settings.py. What could be the reason? -
How to Display Total Object Count in Wagtail Snippet ViewSet?
I am currently developing a Wagtail project where I use the ModelAdmin to create custom admin interfaces for my models. When using ModelAdmin, the total object count of a model is displayed below the model name in the list view. However, when I switched to using SnippetViewSet, I lost this functionality.I would like to display the total object count in the list view based on the custom get_queryset method defined in my SnippetViewSet class. ModelAdmin: SnippetViewSet: class PidProviderViewSet(SnippetViewSet): model = PidProvider icon = 'folder' list_display = ["v3", "created"] menu_name = "Unloaded Objects PidProvider" def get_queryset(self, request): qs = PidProvider.objects.filter(foo='foo') return qs register_snippet(PidProviderViewSet) -
Django where to store model-level variables
So I have my model: from django.db import models x_default_coordinate = 0 y_default_coordinate = 0 class Model(models.Model): location1 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) location2 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) Where would be an appropriate place to store the default coordinates? Currently I have them as shown, but that doesn't seem right. -
Sum an aggerated value in Django
I'm trying to achieve the following SQL query in Django: (The table contains the purchases per each day per each location. I want to get the biggest amount of each location, then group them by state to see how much is the max that can be sold in each state) select state, type, sum(amount) from ( select l.state, dd.type, max(amount) as amount from daily_data dd join locations l on l.id = dd.location_id where dd.type in ('purchases', 'returns') group by dd.location_id, dd.type ) group by state, type Where I get this: NY,purchases,80 NY, returns,6 Maine,purchases,125 Maine, returns,12 But I'm geting stuck on how to achieve that in django. I tried this: daily_data.objects.filter(type__in=['purchases', 'returns'] ).values('location', 'type' ).annotate(total=Max('amount') ).values('location__state','type' ).annotate(sum=Sum('total')) But I get an error django.core.exceptions.FieldError: Cannot compute Sum('total'): 'total' is an aggregate I even tried a subquery, but this is generating a bad sql query which yields the query taking forever. subquery = daily_data.objects.filter( location=OuterRef('location'), type=OuterRef('type') ).values('location', 'type').annotate( max_amount=Max('amount') ).values('max_amount') annotated_data = daily_data.objects.filter( type__in=['purchases', 'returns'] ).annotate( max_amount=Subquery(subquery) ).values( 'location__state', 'type' ).annotate( total_max_amount=Sum('max_amount') ).order_by('location__state', 'type') This generates: SELECT "state", "type", SUM(( SELECT MAX(U0."amount") AS "total" FROM "daily_data" U0 INNER JOIN "locations" U1 ON (U0."location_id" = U1."id") WHERE (U1."state" = ("state") AND U2."type" = … -
My partner and I are running the same code, but mine is the only one not working on my local server
We are working with Django to perform an asynchronous export task that will populate a CSV with information and then download the CSV automatically to the user's Downloads once a user hits the button 'Start Export.' When it comes time to run the server and test the download, their CSV downloads immediately upon hitting the export button and mine stays stuck, resulting in infinite XMLHttpRequest's (I eventually have to stop running server), as pictured below. Naturally, their Safari network shows only one XHR before it downloads. Infinite XHR's We have pulled the same code and I have matched up my Python version and package downloads to theirs. I have also made sure I cleared cache, tried different browsers, and allowed all popups on my browser. I have also confirmed that the async task successfully results in a CSV when I test on the shell. I have also recreated the virtual environment multiple times. I've been tearing my hair out about this for 8 hours a day for the past week. Any pointers would be appreciated! Thank you. -
How to implement Django WebSockets?
I'm trying to create a simple Django app, using websockets for sending data. According to the documentation: I've added 'channels' in settings.py's INSTALLED APPS: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "channels", "serial_mouse", ] ASGI_APPLICATION = 'mouse_serial.asgi.application' Created asgi.py file, to configure ASGI: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from serial_mouse import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mouse_serial.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) Set up routing.py for websockets: from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/serial/', consumers.SerialConsumer.as_asgi()), ] Implemented the WebSocket consumer in the newly created consumers.py: import json import asyncio import os import serial import cv2 import time from django.conf import settings from channels.generic.websocket import AsyncWebsocketConsumer from .models import Capture, MouseData class SerialConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.serial_task = None async def connect(self): await self.accept() self.serial_task = asyncio.create_task(self.read_serial()) async def disconnect(self, close_code): self.serial_task.cancel() async def receive(self, text_data): data = json.loads(text_data) if data['action'] == 'capture': self.capture_image() elif data['action'] == 'mouse_move': self.save_mouse_data(data['x'], data['y']) async def read_serial(self): ser = serial.Serial('/dev/ttyUSB0', 9600) while True: line = ser.readline().decode('utf-8').strip() await self.send(text_data=json.dumps({ 'message': line, })) @staticmethod def capture_image(): cam = cv2.VideoCapture(0) ret, frame = cam.read() … -
The debug toolbar is not displayed - docker - django
) I hope you be well... well! I just installed debug toolbar for my django project like allways. but I don't know why doesn't the debug toolbar display?! and I have to add that I'm using docker and it's my first time that use docker. I think I should do something with docker... I have no ideas:) I also run "docker-compose up --build" but nothing and nothing -
Field is filled but still get ValidationError this field is required in
I want to create User using User.objects.create_user and I am using some fields of a form Utilisateurs to do that. The image field and username field from this form are also used to populate a model UserProfile. In views py def sign_in(request): form=Utilisateur(request.GET) if request.method=="POST": form=Utilisateur(request.POST) if form.is_valid(): User.objects.create_user(username=form.cleaned_data["username"], password=form.cleaned_data["password"], first_name=form.cleaned_data["first_name"], last_name=form.cleaned_data["last_name"], email=form.cleaned_data["email"] ) UserProfile.objects.create(username=form.cleaned_data["username"],profile_img=form.cleaned_data["profile_img"]) return redirect("home") else: print(form.errors.as_data()) context={"form":form} return render(request,'signin.html',context) In models.py class UserProfile(models.Model): username=models.CharField(max_length=50) profile_img=models.ImageField(default="images/logo.png", upload_to="images/",blank=True, null=True) date = models.DateField(default=django.utils.timezone.now()) In forms.py class Utilisateur(forms.Form): first_name=forms.CharField(min_length=4,max_length=15,label="Nom",widget=(forms.TextInput(attrs={"class":"userclass"}))) last_name = forms.CharField(min_length=4, max_length=15,label="Prenom",widget=(forms.TextInput(attrs={"class":"userclass"}))) username=forms.CharField(min_length=4, max_length=15,label="Nom d'uttilisateur",widget=(forms.TextInput(attrs={"class":"userclass"}))) email=forms.EmailField(label="Email",widget=(forms.EmailInput(attrs={"class":"userclass"}))) password=forms.CharField(label="Mot de passe",widget=(forms.PasswordInput(attrs={"class":"userclass"}))) profile_img = forms.ImageField(label="Image de Profile") class ProfileForm(forms.Form): profile_img = forms.ImageField(label="Image de Profile", required=False) Error printed out: {'profile_img': [ValidationError(['This field is required.'])]} -
"No errors found by the IDE" in problems tab
My PyCharm always shows: "No errors found by the IDE" I don't open power save mode. I don't know why. I even reinstalled PyCharm and shut down all plugins, however, my idea doesn't work well. I have search this problem on the internet but without finding any solution. -
I'm unable to run my django application, but nothing happens
I have a django project and I'm trying to run it with '''python manage.py runserver ''' but nothing really happens. I was working on it just 5 mins before this happens. Now, I'm unable to run anything, my project doesn't even show on the github desktop version... anyone has any ideas ? I've tried to check django, python, Running Processes, everything is okey. I'm not able to Run Django Shell neither.enter image description here -
how to show user in TokenSerializer dj-rest-auth
I'm trying to return UserSerializer after successful login through dj-rest-auth. I followed the steps that were told in After login the `rest-auth`, how to return more information? which has a similar issue, but it still doesn't show information about User after logging in. what i'm getting after successful login REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': 'blink.user.serializers.TokenSerializer', 'USER_DETAILS_SERIALIZER': 'blink.user.serializers.UserSerializer' } #settings.py class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): exclude_fields = kwargs.pop('exclude_fields', None) super(UserSerializer, self).__init__(*args, **kwargs) if self.context and 'view' in self.context and self.context['view'].__class__.__name__ == 'UsersView': exclude_fields = ['subscription', 'avatar', 'file'] if exclude_fields: for field_name in exclude_fields: self.fields.pop(field_name) class Meta: fields = ('id', 'username', 'email', 'last_login', 'first_name', 'last_name') model = User class TokenSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TokenModel fields = '__all__' #User.serializers.py -
Post.objects.all() not working as i wished
Hey I am currently going through the Django tutorials and I am trying to display all of my Post objects in the python shell using from blog.models import Post Post.objects.all() my model is from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title It should display ` [<Post: Blog 1>, <Post: Blog 2>] instead of [<Post: Post object (1)>, <Post: Post object (2)>] It just says "Post object" instead of the title. What is the reason why? I have been following the tutorial exactly and can't understand why it displays it like that. It's hard to organize all of the posts when it says "Post object" for all of them. I am using the latest version of python and django. -
ReactJS useParams for Django equivalent?
Django Example # urls.py url = [ path('password_reset/<uidb64>/<token>/', views.password_reset_confirm, name='password_reset_confirm'), ] # views.py def password_reset_confirm(request, id, token): print(id) print(token) pass How would I create an equivalent for ReactJS?? // App.js <Route path='password_reset/:uid/:token' element={<PasswordResetPage/>} /> // PasswordResetPage.js ???? -
Custom Django Transform with case statement for casting a string to either int or null
I'm trying to create a custom django lookup as_int so that you can easily compare and order the contents of text fields when they contain only a number, and treat them as NULL when they have the wrong format. For example: Comment.objects.filter(body__as_int__gt=5) # Should treat a comment with body="37" as 37 # Should treat a comment with body="abc" as NULL This is what I have so far: class AsIntTransform(Transform): lookup_name = "as_int" output_field = models.IntegerField() def as_sql(self, compiler, connection): case_expr = Case( When( Regex(self.lhs, r"^\d+$"), then=Cast(self.lhs, models.IntegerField()), ), default=Value(None), ) return case_expr.as_sql(compiler, connection) models.CharField.register_lookup(AsIntTransform) models.TextField.register_lookup(AsIntTransform) Trying to filter with the above code is throwing: field_list = name.split(LOOKUP_SEP) ^^^^^^^^^^ AttributeError: 'Col' object has no attribute 'split' It looks like the 'Col' its referring to here is self.lhs in the transform, but I'm not sure what I'm supposed to change to make this work? -
Django errorlist in form Select Valid Choice
The situation is as follows: I am building a form where I fetch data for some fields from an API. I have tried debugging in every possible way, but I cannot understand why the data is not being persisted in the database. Whenever I click submit, I get the following error: <ul class="errorlist"><li>municipio<ul class="errorlist"><li>Select a valid choice. Afuá is not one of the available choices.</li></ul></li></ul> If anyone can help me understand why this error is occurring, I would appreciate it. To provide context, I am sharing the three main files. My models.py: # apps/parametrizacao/models.py from django.db import models class RegraFiscal(models.Model): REGIME_TRIBUTARIO_CHOICES = [ ('Simples Nacional', 'Simples Nacional'), ('Lucro Presumido', 'Lucro Presumido'), ('Lucro Real', 'Lucro Real'), ('Misto', 'Misto') ] PORTE_CHOICES = [ ('ME', 'Microempresa (ME)'), ('EPP', 'Empresa de Pequeno Porte (EPP)'), ('Demais', 'Demais') ] nome = models.CharField(max_length=255, default='Padrão') regime_tributario = models.CharField(max_length=20, choices=REGIME_TRIBUTARIO_CHOICES) porte = models.CharField(max_length=10, choices=PORTE_CHOICES, default='ME') aliquota_csll = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_irpj = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_pis = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_cofins = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_icms = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_ipi = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_iss = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_inss = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __str__(self): return f"{self.nome} - {self.porte}" class Empresa(models.Model): nome = models.CharField(max_length=255) cnpj = models.CharField(max_length=18) … -
How to debug HTTP 400 Bad Request errors in django?
I have an app with React frontend and Django backend. I'm trying to make a POST request from my react client but I get "Bad Request" error. I checked my request url and it matches with my api url. Therefore I believe the error has to do with the data I pass. How can I debug this error to learn more about it? Here are the necessary code parts: models.py class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="products") def __str__(self): return self.name class BatchChain(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField() class Batch(models.Model): # This is the model I'm trying to POST product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="batches_from_products") chain = models.ForeignKey(BatchChain, on_delete=models.CASCADE) serializers.py class BatchPostSerializer(serializers.ModelSerializer): class Meta: model = Batch fields = ["id", "product", "chain"] views.py class BatchListCreate(generics.ListCreateAPIView): serializer_class = BatchPostSerializer permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user batches = Batch.objects.filter(product__owner=user) return Batch.objects.filter(chain__in=batches.values_list("chain")) def perform_create(self, serializer): if serializer.is_valid() is False: return Response({'Message': 'Serializer is not valid'}, status=status.HTTP_400_BAD_REQUEST) if Batch.objects.filter(chain=self.request.data["chain"]).exists(): return Response({'Message': 'You can not create a second batch with same chain'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) serializer.save() api/urls.py ... path("batches/", views.BatchListCreate.as_view(), name="batch-list-create"), # all calls to /api/ are directed to this folder ... … -
Validation in DR(Django)
I'm trying create customs validations to my serialiazer but Django just ignore them and return me DRF default errors. {'message': 'Erro ao criar camião', 'data': {'plate': [ErrorDetail(string='This field may not be null.', code='null')]}} That's the answer i get view.py View that allow companies to add their trucks class TruckView(generics.GenericAPIView): permission_classes = [IsAuthenticated, IsCompanyAuthenticated] queryset = Trucks.objects.all() serializer_class = TruckSerializer def post(self, request): company = get_object_or_404(Company, user=request.user) request.data['company'] = company.id request.data['on_service'] = False serializer = TruckSerializer(data=request.data) if serializer.is_valid(raise_exception=False): serializer.save() return Response( { 'message': "Camião criado com sucesso", 'data': serializer.data }, status=status.HTTP_201_CREATED ) else: print(serializer.data) return Response( { 'message': "Erro ao criar camião", 'data': serializer.errors }, status=status.HTTP_400_BAD_REQUEST ) Serializer.py class TruckSerializer(serializers.ModelSerializer): company = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all()) types = TypesSerializer(many=True, read_only=True) class Meta: model = Trucks fields = '__all__' def validate(self, attrs): return super().validate(attrs) def validate_required_field(self, value, error_message): if not value or value in [None, "", " ", []]: raise ValidationError(error_message) return value def validate_plate(self, value): return self.validate_required_field(value, "Matricula inválida") def validate_types(self, value): for type_id in value: try: # Get the Types instance by ID Types.objects.get(id=type_id['id']) except Types.DoesNotExist: # Handle the case where the type ID is not valid raise serializers.ValidationError("Tipo de veículo inválido") return self.validate_required_field(value, "Introduza tipo válidos para este camião") def validate_policy_nr(self, value): … -
Django app deployed to under the url subdirectoly
In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.example.com/company/playground/* -> https://amazonloadbalancer/* However, there comes a few problem,such as Problem 1 static Access https://www.exmplae.com/company/playground/top will be jumped to https://amazonloadbalancer/top correctly, but static file url will be https://www.exmplae.com/static/main.js while the real file is located https://www.example.com/company/playground/static/main.js /company/playground is omitted so, can not be reached. Problem 2 admin transfered accesing https://www.example.com/company/playground/admin the url is transferred by django to https://www.example.com/admin/login/?next=/admin/ /company/playground is omitted again, so can not be reached. Is there any good setting for this purpose?? -
Django Inline Formset data not saving
I have created an inline formset which works exactly as I planned on the frontend side- However I can't seem to access any of the data- it seems like the form isn't saving the data? Here in the views.py you can see where it should be saving: def formset_variantingredients_valid(self, formset): variantingredients = formset.save(commit=False) for variantingredient in variantingredients: variantingredient.recipe = self.object variantingredient.save() def formset_images_valid(self, formset): images = formset.save(commit=False) for image in images: image.recipe = self.object image.save() In the admin, in my saved form I can only see the standard fields that have saved and not either of these two inline formsets- Is my issue in the saving of the form itself or am I just not accessing the data correctly? Many Thanks for the help! -
Is the batch processing speed of Python slower than that of Java?
I am working on migrating a function implemented in Java Spring Boot to Python Django. I encountered an issue while migrating a function that retrieves a list of keywords through a select query and updates these keywords using an update query. Specifically, updating 450 rows takes around 0.1 seconds in Java, but it takes 2 seconds in Python. Below are the methods I used to measure the time and the Java and Python code. Measurement method // java long startTime = System.nanoTime(); // Execute the update long endTime = System.nanoTime(); double duration = (endTime - startTime) / 1_000_000_000.0;; String formattedDuration = String.format("%.2f seconds", duration); log.info("processing_time: {}", formattedDuration); // python start_time = time.perf_counter() // Execute the update end_time = time.perf_counter() processing_time = end_time - start_time processing_time_formatted = f"{processing_time:.2f}" logger.info(f"processing_time: {processing_time_formatted} seconds") Logic Java // application.yml spring: datasource: driver-class-name: org.mariadb.jdbc.Driver url: jdbc:mariadb:... username: ... password: ... jpa: hibernate: ddl-auto: none properties: hibernate: show_sql: true use_sql_comments: true format_sql: true dialect : org.hibernate.dialect.MariaDBDialect open-in-view: false sql: init: mode: never // service public void updateUserIntrKwd(String indvNum) { // 2s List<IntrKwdDto> kwdList = intrKwdMapper.selectIntrKwdList(indvNum); // 0.001s DatesAndMaxFrequency datesAndMaxFrequency = getDatesAndMaxFrequency(kwdList); // 0.1s intrKwdMapper.updateUserIntrKwd(kwdList, datesAndMaxFrequency); } // Mapper <update id="updateUserIntrKwd" parameterType="map"> <foreach collection="kwdList" item="item" separator=";"> ... Python … -
AJAX Filtering with jQuery and Django Not Updating Product List
I am working on a project where I need to filter products based on selected categories and vendors using AJAX with jQuery and Django. However, despite no errors in the console, the product list is not updating as expected. Here are the relevant parts of my code: JavaScript: $(document).ready(function(){ $(".filter-checkbox").on("click",function(){ console.log("A checkbox have benn clicked"); let filter_object = {} $(".filter-checkbox").each(function(){ let filter_value = $(this).val() let filter_key = $(this).data("filter") // console.log("Filter value is:", filter_value); // console.log("Filter key is:", filter_key); filter_object[filter_key] = Array.from(document.querySelectorAll('input[data-filter = '+ filter_key +']:checked')).map(function(element){ return element.value }) }) console.log("Filter object is:", filter_object) $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function(){ console.log("Trying to filter Product...") }, success: function(response){ console.log(response); console.log("Data filtered successfully..."); $("#filtered-product").html(response.data) } }) }) }) Django Views: def filter_product(request): categories = request.GET.getlist("category[]") vendors = request.GET.getlist("vendor[]") products = Product.objects.filter(product_status="published").order_by("-id").distinct() if len(categories) > 0: products = products.filter(cagtegory__id__in = categories).distinct() if len(vendors) > 0: products = products.filter(vendor__id__in = vendors).distinct() context = { "products":products } data = render_to_string("core/async/product-list.html",context) return JsonResponse({"data":data}) Template: <div class="showcase" id="filtered-product"> {% for p in products %} <div class="showcase-banner"> <img src="{{p.image.url}}" width="300" class="product-img default"> <img src="{{p.image.url}}" width="300" class="product-img hover"> <p class="showcase-badge">15%</p> <div class="showcase-actions"> <button class="btn-action"> <ion-icon name="heart-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="eye-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="repeat-outline"></ion-icon> </button> …