Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OSError: [Errno 24] Too many open files even after using with context manager
I've a Django application running on a server I'm using gunicorn on server this what my gunicorn service file looks like myapp.service [Unit] Description=myapp daemon Requires=myapp.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/myappApi/ ExecStart=/myappApi/venv/bin/gunicorn \ --access-logfile - \ --workers 10 \ --timeout 0 \ --bind unix:/run/myapp.sock \ myappProject.wsgi:application [Install] WantedBy=multi-user.target and this is the error I'm getting File "/myappApi/views.py", line 293, in CustomHandler Jan 23 10:48:30 myapp gunicorn[2957207]: app = CustomApp() Jan 23 10:48:30 myapp gunicorn[2957207]: File "app.py", line 22, in __init__ Jan 23 10:48:30 myapp gunicorn[2957207]: self.logger = start_logger(__file__) Jan 23 10:48:30 myapp gunicorn[2957207]: File "utils/loggerUtil.py", line 19, in start_logger Jan 23 10:48:30 myapp gunicorn[2957207]: OSError: [Errno 24] Too many open files: 'conf/config.json' above error is raised by this code from logging.handlers import RotatingFileHandler import os, logging, time, json def start_logger(__file__): os.makedirs('logs', exist_ok=True) fileName = os.path.basename(__file__) logdatetime = time.strftime("%d-%m-%Y-%I-%M") logFilename = 'logs/' + fileName[:-3] + logdatetime + '.log' logger = logging.getLogger(__file__) ''' Setting the threshold of logger to DEBUG ''' with open("conf/config.json") as f1: data = json.load(f1) # Rotating handler handler = RotatingFileHandler( logFilename, maxBytes=data['maxBytes'], backupCount=data['backupCount']) logger.addHandler(handler) return logger I've checked this answer it increases ulimit of a file which is okay but It's a temporary solution. I've noticed I'm using … -
Django: How to Represent and Query Symmetrical Relationships for a Family Tree?
I am building a family tree application in Django where I need to represent and query marriages symmetrically. Each marriage should have only one record, and the relationship should include both partners without duplicating data. Here's the relevant model structure: class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) spouses = models.ManyToManyField( 'self', through="Marriage", symmetrical=True, related_name="partners" ) class Marriage(models.Model): person1 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="marriages_as_person1") person2 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="marriages_as_person2") start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) I want to: Ensure both partners appear as spouses for each other symmetrically. Avoid duplicate entries for the same marriage. Efficiently query all spouses of a person. Here’s the code I’m using to query spouses: # Query spouses for a person p1 = Person.objects.create() p2 = Person.objects.create() Marriage.objects.create(person1=p1, person2=p2) p1.spouses.all() # Returns list containing p2 p2.spouses.all() # Returns empty list However, I’m facing challenges: If p1 spouses are queried, it should contain p2 and if p2 spouses are queried, it should contain p1 Both queries are not symmetrical Questions: Is my model structure correct for representing marriages symmetrically? If not, what improvements should I make? How can I efficiently query all spouses of a person in a database-optimized way while ensuring symmetry? -
Django: rest endpoint not found
I am trying to implement a rest endpoint with Django. My views.py is: from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status import json from .utils import retrieve_and_detect_faces @api_view(["POST"]) def video_analysis(request): data = json.loads(request.body) timestamp = data.get("timestamp") return JsonResponse({....}) And in urls.py: from django.urls import path from .views import video_analysis urlpatterns = [ path('video_analysis/', video_analysis, name = 'video_analysis') ] But when I try to call this endpoint, I get error: Not Found: /video_analysis [24/Jan/2025 07:37:26] "POST /video_analysis?timestamp=1234567 HTTP/1.1" 404 2262 What configuration am I missing in my program? -
AllAuth.url is not working and not showing path sugestions
Setting.py: INSTALLED_APPS = [ 'channels', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', "allauth.account.middleware.AccountMiddleware", 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] File: url.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] Like, I just followed the quickstart of all auth, and I've done this once before with a tutorial, but this time something went wrong because when I search for : localhost:8000/accounts/ it says the path doesn't exists, instead of giving me suggestions of follow up. And when I go localhost:8000/ it does suggest admin/, accounts/ -
BadRequest can't return JSON?
I am trying to return a JSON object along with a 400 error code. This correctly returns the object (e.g. {"email": ["A user with that email address already exists."]}: return HttpResponse(json.dumps(dict(form.errors.items()))) Whereas these all just returns an unreadable (by javascript) object ([object Object]): return BadRequest(json.dumps(dict(form.errors.items()))) return HttpResponseBadRequest(json.dumps(dict(form.errors.items()))) return BadRequest(json.dumps(dict(form.errors.items())), content_type='application/json') I've tried several other methods of sending an error code but the results were the same. How do I get the readable object along with a 400 Bad Request error code? -
How to configure dynamic language switching for API responses using i18n_patterns in Django?
I am working on a Django project and need to implement multilingual support for my REST API. I want the API to return responses in the selected language based on the URL prefix (e.g., /en/, /ml/) using i18n_patterns. I’ve done the following: In settings.py, I’ve defined the available languages: LANGUAGES = [ ('en', 'English'), ('ml', 'Malayalam'), ] LANGUAGE_CODE = 'en' I’ve added 'django.middleware.locale.LocaleMiddleware' to the MIDDLEWARE setting: MIDDLEWARE = [ ... # other middlewares 'django.middleware.locale.LocaleMiddleware', ] In the project’s urls.py, I’ve used i18n_patterns to ensure the URLs are prefixed with the language code: from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('accounts.urls')), path('app/', include('app.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = i18n_patterns(*urlpatterns) The Issue: While I can specify the language via the URL (e.g., /ml/ for Malayalam), the API responses are not being automatically translated to the selected language. The responses remain in English even when the Accept-Language header or language prefix is set to another language (e.g., Malayalam) What I Expect: I expect the API responses to be auto-translated into the selected language (e.g., Malayalam) based on the URL prefix or Accept-Language header. What I Have Tried: I’ve confirmed that LocaleMiddleware is active in MIDDLEWARE. I’ve ensured that … -
How to display video of cloudnary in admin panel and play
So, I am using cloudinary in django for video handling. video handling is going very well but i want to display video on admin panel. models.py course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='Course') public_id = models.CharField(max_length=130, blank=True, null=True) title = models.CharField(max_length=120) description = models.TextField(max_length=500, blank=True, null=True) thumbanil = CloudinaryField( "image", blank=True, null=True, public_id_prefix=get_public_id_prefix, display_name=get_display_name, tags=get_tags ) video = CloudinaryField( "video", blank=True, null=True, type='private', resource_type="video", public_id_prefix=get_public_id_prefix, display_name=get_display_name, tags=get_tags ) admins.py import helpers from cloudinary import CloudinaryImage from django.contrib import admin from .models import Course, Lesson from django.utils.html import format_html class LessonInline(admin.StackedInline): model = Lesson fields = ['public_id', 'title', 'description', 'thumbanil', 'display_thumbnail' , 'video', 'display_video_content', 'order', 'can_preview', 'status', 'updated', 'timestamp'] readonly_fields = ['public_id', 'updated', 'timestamp', 'display_thumbnail', 'display_video_content'] extra = 0 # means number of empty forms display in admin panel for adding lessons ok. def display_video_content(self, obj): url = helpers.get_cloudinary_video_object( obj, field_name="video", as_html=False, width=400, height=350, sign_url=False, fetch_format="auto", quality="auto" ) return format_html(f"<source src='{url}' type='video/mp4' /sourse>") display_video_content.short_description = 'Current Video' helper/server.py def get_cloudinary_video_object( instance, field_name="video", as_html=False, width=None, height=None, sign_url=False, # for private videos fetch_format="auto", quality="auto" ): if not hasattr(instance, field_name): return "" video_objest = getattr(instance, field_name) # give the value of instance fielsname if match with inatance if not video_objest: return "" video_options = { "sign_url": … -
apache2 not runing django error ImportError: No module named site
sudo vi /etc/httpd/conf.d/canon.conf <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName your_domain_or_ip # Path to the root of your Django app DocumentRoot /home/ec2-user/erp-edi-integration/canon # Update to the new virtual environment path WSGIDaemonProcess canon python-home=/home/virtual-env/venv WSGIProcessGroup canon WSGIScriptAlias / /home/ec2-user/erp-edi-integration/canon/canon/wsgi.py # Set up static files Alias /static/ /home/ec2-user/erp-edi-integration/canon/static/ <Directory /home/ec2-user/erp-edi-integration/canon/static> Require all granted </Directory> # Set up media files Alias /media/ /home/ec2-user/erp-edi-integration/canon/media/ <Directory /home/ec2-user/erp-edi-integration/canon/media> Require all granted </Directory> <Directory /home/ec2-user/erp-edi-integration/canon/canon> <Files wsgi.py> Require all granted </Files> </Directory> canon/wsgi.py import os, sys sys.path.insert(0, '/home/ec2-user/erp-edi-integration/canon') sys.path.insert(0, '/home/virtual-env/venv/lib/python3.9/site-packages') sys.path.insert(0, '/home/virtual-env/venv/lib/python3.9/lib-dynload') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'canon.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() >>> import sys >>> print(sys.path) ['', '/home/ec2-user/miniconda3/envs/myenv/lib/python39.zip', '/home/ec2-user/miniconda3/envs/myenv/lib/python3.9', '/home/ec2-user/miniconda3/envs/myenv/lib/python3.9/lib-dynload', '/home/virtual-env/venv/lib/python3.9/site-packages'] all requirement already install check virtual environment source /home/virtual-env/venv/bin/activate # Activate again after all this when i run my server restart then in apache log error show me this ImportError: No module named site what is wrong in this my project path is /home/ec2-user/erp-edi-integration/canon/canon/wsgi.py -
I want to make a dropdown item send data to a form, help needed
I have this dropdown that fills itself with the make of cars inside my database and i want to make each one of the items(when selected) send their name to a dorm (ex: if i press Fiat i want the item to send the name Fiat to the form). I would appreciate any help :) Also if you saw a post with a similar question let me know, thanks :) Here is the code i got: {% extends "layout.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}?v=1"> <!-- search bar for advanced search--> <div class="container-search"> <br> <h1 class="text-center text-white">Search Cars</h1> <hr> <form method="get" action="{% url 'search' %}"> <!-- Dropdowns - Side by side --> <div class="d-flex justify-content-center mb-3"> <div class="dropdown me-3"> <button class="btn btn-danger dropdown-toggle" type="button" id="makeDropdown" data-bs-toggle="dropdown" aria-expanded="false"> Select Make </button> <ul class="dropdown-menu" aria-labelledby="makeDropdown"> {% for make in car_makes %} <post value="{{make.make}}" name="{{ make.make }}" class="text-dark">{{ make.make }}</post> <br> {% endfor %} </ul> </div> <div class="dropdown"> <button class="btn btn-danger dropdown-toggle" type="button" id="modelDropdown" data-bs-toggle="dropdown" aria-expanded="false"> Select Model </button> <ul class="dropdown-menu" aria-labelledby="modelDropdown"> {% if cars != None %} {% for car in cars %} <option value="{{ car.model }}" class="text-dark">{{ car.model }}</option> {% endfor %} … -
Custom generic istruthy/isfalsy lookup doesn't work on Foreign Keys
In my Django project, I'm in need of a generic istruthy/isfalsy lookup that would work on any type of database field. Example of models.py: class MyModel(models.Model): my_charfield = models.CharField(...) my_decimalfield = models.DecimalField(...) my_datefield = models.DateField(...) my_boolfield = models.BooleanField(...) my_fkfield = models.ForeignKey(...) What I want to be able to do: MyModel.objects.filter(my_charfield__isfalsy=True) MyModel.objects.filter(my_decimalfield__isfalsy=True) MyModel.objects.filter(my_datefield__isfalsy=True) MyModel.objects.filter(my_boolfield__isfalsy=True) MyModel.objects.filter(my_fkfield__isfalsy=True) I have defined two custom lookups to do that: from django.db.models import Lookup, BooleanField, ForeignKey, Field class IsTruthy(Lookup): lookup_name = 'istruthy' def as_sql(self, compiler, connection): lhs, params = self.process_lhs(compiler, connection) if isinstance(self.lhs.output_field, BooleanField): return f"{lhs} = TRUE", params if isinstance(self.lhs.output_field, ForeignKey): lhs = f"{lhs}_id" return f"{lhs} IS NOT NULL", params return f"{lhs} IS NOT NULL AND {lhs} <> ''", params class IsFalsy(Lookup): lookup_name = 'isfalsy' def as_sql(self, compiler, connection): lhs, params = self.process_lhs(compiler, connection) if isinstance(self.lhs.output_field, BooleanField): return f"{lhs} = FALSE", params if isinstance(self.lhs.output_field, ForeignKey): lhs = f"{lhs}_id" return f"{lhs} IS NULL", params return f"{lhs} IS NULL OR {lhs} = ''", params Field.register_lookup(IsTruthy) Field.register_lookup(IsFalsy) These custom lookups work on all fields except ForeignKey. When used on a ForeignKey, the following error is triggered: django.core.exceptions.FieldError: Unsupported lookup 'isfalsy' for ForeignKey or join on the field not permitted I have tried different variations of this code to handle … -
Temporarily load a fixture for development
I would like to create a lot of dummy products for use in development. The dummy products need to be in the development database, in addition to a copy of all of the data that the production database has, so that I can see what the dummy products will look like in the website. How can I do this easily? I've looked into fixtures, but I can't figure out how to "apply" a fixture on top of a copy of the production database, and how I might be able to unapply it when I'm done with that part of development. -
Is this djoser implementation secure?
This question may be too broad for StackOverflow, but I'm not sure where else to go for help. I wrote a simple authentication system in Django with Djoser and its JWT implementation, using jQuery on the frontend. I really don't know what I'm doing though, and I'm about 99% sure I did it wrong and it's totally insecure. First, when a user submits the login form, I send a POST request to retrieve a refresh token and an access token. The refresh token is stored as a cookie, and the access token is stored in sessionStorage: // Post the form $.post("/auth/jwt/create/", $(this).serialize()) // Success: store tokens & redirect .done(function(data) { // Logged in: set redirect path & store tokens if (data.refresh !== "undefined" && data.access !== "undefined") { Cookies.set("refresh_token", data.refresh, { expires: 30, secure: true, sameSite: "strict" }); sessionStorage.setItem("access_token", data.access); } }) I have another simple script that runs every time a page is loaded. There, I verify the access token, attempt a refresh if it's invalid, fetch user data using the access token, then post that user data to the backend to login. This script also logs the user out if on the logout page: // Log in or … -
Data not saved to database
I don't know what's going on here, whenever I try to create a buzz with the status set to Draft (this is also the default status set on the model) Django returns a 302 response and does not saved it to the database. However, when I change the status to Published it just saves it normally on the database. Here's the code to the view def buzz_create(request): form = BuzzCreateForm() if request.method == 'POST': form = BuzzCreateForm(data=request.POST) if form.is_valid: buzz = form.save(commit=False) buzz.author = request.user buzz.save() return redirect(to=reverse('buzz:buzz_list')) return render( request=request, template_name='buzz/create.html', context={ 'form': form } ) Here's the code to the model: class BuzzPublishedManager(models.Manager): def get_queryset(self): return ( super().get_queryset().filter(status=Buzz.Status.PUBLISHED) ) class Buzz(models.Model): class Status(models.TextChoices): PUBLISHED = 'PBL', 'Published' DRAFT = 'DFT', 'Draft' title = models.CharField(max_length=250) body = models.TextField() slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buzzes' ) status = models.CharField( max_length=3, choices=Status, default=Status.DRAFT ) published = BuzzPublishedManager() objects = models.Manager() class Meta: verbose_name_plural = 'Buzzes' ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']) ] def __str__(self): return self.title The objects in the model was not there before. I tried adding it maybe the data is saved but not queried … -
Django Allauth's Google Login Redirect and Page Design
Currently, on the login page, I have a button: <div class="d-grid gap-2"> <a href="{% provider_login_url 'google' %}" class="btn btn-danger"> <i class="fab fa-google"></i> Sign in with Google </a> </div> This redirects to accounts/google/login/, and that page allows for redirection to Google authentication. I have two problems: I don't know if these two steps are necessary and I don't see the value of having the extra step accounts/google/login/. I don't know how to replace the standard layout of the accounts/google/login/ page (in case it is really needed). -
Access request session data of DetailView in CreateView in django
I am writing a library management system in Django. There are two views that I am having a bit of a struggle. The BookDetailsView lists the details of a Book such as title, price, etc. class BookDetailsView(LoginRequiredMixin, DetailView): model = Book template_name = 'book_detail.html' def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) request.session['book_pk'] = kwargs['pk'] return response # used to mark book as read or unread def post(self, request, *args, **kwargs): if 'is_read' in request.POST: book = Book.objects.get(pk=kwargs['pk']) book.is_read = True book.save() return HttpResponseRedirect(self.request.path_info) In the BookBorrowView, I display a form where the reader can borrow a book. Two fields are preset (borrowers and book), and I don't want the user to be able to change them. At the moment, the user can select among many options. class BookBorrowView(LoginRequiredMixin, CreateView): model = BookBorrowTransaction template_name = 'book_borrow.html' fields = ['book', 'borrowers', 'date_borrowed', 'to_return', ] success_url = reverse_lazy('home') def get_initial(self): initial = super(BookBorrowView, self).get_initial() initial['borrowers'] = get_object_or_404(CustomUser, email=self.request.user.email) initial['book'] = get_object_or_404(Book, title=Book.objects.get(pk=self.request.session['book_pk']).title) # need the book id here print(self.request.GET) print(self.request.POST) print(self.request.session['book_pk']) return initial The following is a screenshot of the form displayed by the BookBorrowView. I have two questions: I am passing the primary key for the book through request.session … -
Export command not found in working django import-export app
I'm trying to reproduce the export command as shown in the import-export docu python manage.py export CSV auth.User yet all I get is: Unknown command: 'export'. Type 'manage.py help' for usage. Besides the management command, the import-export api works fine -
Django: Unable to login into a account
I have created a custom user model in my django model where the password is being saved using make_password from password_strength but when trying to login using the check_password it says invalid username or password. @csrf_exempt def login_attempt(request): if request.method == 'POST': try: data = json.loads(request.body) email = data.get('email') password = data.get('password') try: user_obj = user.objects.get(email=email) except user.DoesNotExist: return JsonResponse({'success': False, 'message': "Email doesnot exists"}, status=401) if check_password(password, user_obj.password): login(request, user_obj) return JsonResponse({'success': True, 'message': "Login successful"}, status=200) else: return JsonResponse({'success': False, 'message': "Invalid email or password"}, status=401) except Exception as e: return JsonResponse({'success': False, 'message': f"Error: {str(e)}"}, status=500) return JsonResponse({'success': False, 'message': "Invalid request method"}, status=405) -
SAP Connection failed: name 'Connection' is not defined, PYRFC in django
I'm experiencing an issue with the pyrfc library in my Django project running on Pythonanywhere server. Specifically, I am trying to use the Connection class from pyrfc to establish a connection to an SAP system, but I am encountering an ImportError when I try to import Connection in my views.py file. The error message says: SAP Connection failed: name 'Connection' is not defined However, when I test the same code in the Django shell, everything works fine, and the Connection class is correctly imported. I have verified that the environment variables SAP_NWRFC_HOME and LD_LIBRARY_PATH are set correctly, and the libsapnwrfc.so library loads successfully. If i do make import like from pyrfc import Connection then it gives the error 2025-01-22 07:28:52,598: Error running WSGI application 2025-01-22 07:28:52,599: ImportError: cannot import name 'Connection' from 'pyrfc' (/home/moeez007/.local/lib/python3.10/site-packages/pyrfc/__init__.py) 2025-01-22 07:28:52,599: File "/var/www/moeez007_pythonanywhere_com_wsgi.py", line 80, in <module> 2025-01-22 07:28:52,600: from pyrfc import Connection i also have tried to set the environment variables in the wsgi file import os os.environ["SAP_NWRFC_HOME"] = "/home/moeez007/nwrfcsdk" os.environ["LD_LIBRARY_PATH"] = "/home/moeez007/nwrfcsdk/lib" but still the same, i also have tried to run this as a separate file but still the same why is it working in the django shell and python but not … -
How to configure Nginx to serve Django and a Wordpress site on a specific route?
Good day good people of SO! I have a Django app on a Hetzner server and a Wordpress site on a Hostinger server. I want to configure Nginx on my Hetzner server to serve the Django app and when it requests the /route-name route, it serves a Wordpress site from the Hostinger server. I've already allowed the IP address of my Hetzner server to access the Wordpress site. Hetzner server is running Nginx and Hostinger is running Apache2 if that's relevant. I know there are quite a few questions and answers regarding configuring Nginx to serve Django and Wordpress but I've been scouring this forum and the Internet for several hours now with no solution found for my problem. I suspect it may have to do with my Nginx config, but after trying out several configurations accepted on here and elsewhere, I can't seem to make it work. This is what I currently have for my Nginx config: server { location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /var/www/example.com/static/; } location /media/ { alias /var/www/example.com/media/; } # Reverse proxy for /freebies location /route-name/ { proxy_pass http://<IP-ADDRESS OF HOSTINGER SERVER>/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; … -
Failed to start gunicorn.socket: Unit gunicorn.socket has a bad unit file setting
** [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=evanys Group=www-data WorkingDirectory=/home/evanys/www/plus ExecStart=/home/evanys/www/django22/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/home/evanys/plus.sock \ plus.wsgi:application [Install] WantedBy=multi-user.target ** Hola al momento de ejecutar *>sudo systemctl start gunicorn.socket* sale el error *>Failed to start gunicorn.socket: Unit gunicorn.socket has a bad unit file setting.* agradecere alguna solucion -
How to create a Django custom field with different representations in admin, database, and Python code?
I want to create a custom model field in Django that can store values in bytes in the database but allows users to interact with it in gigabytes (GB) in the Django admin interface. The goal is for the field to handle all necessary conversions seamlessly. Specifically, the field should accept input in GB when adding or editing a record in the admin, convert it to bytes before saving it to the database, and then retrieve it in bytes for use in Python code. I’ve started working on this by overriding methods like to_python, get_prep_value, from_db_value, and formfield, but I’m not entirely sure how to structure these methods to ensure the field behaves as intended. Here is what I already have: class GigabyteField(models.BigIntegerField): def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise ValueError(f"Invalid value for GigabyteField: {value}") def get_prep_value(self, value): if value is None: return None return int(value * (1024**3)) def from_db_value(self, value, *args): if value is None: return value return int(value / (1024**3)) -
linux ssh key is available to wsl2 django launched by Windows PyCharm
I am working in a development environment for my Django application where I have PyCharm installed on windows, and I launch django in wsl2. This has been working for me flawlessly for a while now. However just now I have a new need to have an ssh key for 3rd party command line tool my application invokes. I created the key in linux and I can execute the command successfully in a linux terminal, however when my django application runs the command fails with the same error it failed with prior to creating my ssh key. At one point I was 100% confident I had found a workaround of starting ssh-agent and then adding an environment variable to my run configuration to set SSH_AUTH_SOCK to the value of SSH_AUTH_SOCK from my terminal, however over the course of trying to find an actual acceptable solution, I can no longer reproduce this, so I'm unsure if that ever even worked or it worked for another reason that I was not aware of. I can confirm that in this scenario my SSH_AUTH_SOCK does have the correct value in django. Every time the command requiring the ssh key is executed I get an error … -
django s2forms.ModelSelect2Widget not works properly
hi all I’m trying using ModelSelect2Widget I set redis server which I test and it works. then I set the following project: models.py class Doctor(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) status=models.BooleanField(default=True) def __str__(self): return "{} ({})".format(self.user.first_name,self.department) class Patient(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) assignedDoctorId = models.ForeignKey(Doctor, on_delete=models.CASCADE,related_name='doctor_assigned') admitDate=models.DateField(auto_now=True) status=models.BooleanField(default=False) def __str__(self): return self.user.first_name form.py class BaseAutocompleteSelect(s2forms.ModelSelect2Widget): class Media: js = ("admin/js/vendor/jquery/jquery.min.js",) def __init__(self, **kwargs): super().__init__(kwargs) self.attrs = {"style": "width: 300px"} def build_attrs(self, base_attrs, extra_attrs=None): base_attrs = super().build_attrs(base_attrs, extra_attrs) base_attrs.update( {"data-minimum-input-length": 10, "data-placeholder": self.empty_label} ) return base_attrs class DoctorAutocompleteWidget(BaseAutocompleteSelect): empty_label = "-- select doctor --" search_fields = ("username__icontains",) queryset=models.Doctor.objects.all().filter(status=True).order_by("id") class PatientForm(forms.ModelForm): assignedDoctorId=forms.ModelChoiceField(queryset=models.Doctor.objects.all().filter(status=True), widget=DoctorAutocompleteWidget) but results is an empty list enter image description here while using assignedDoctorId=forms.ModelChoiceField(queryset=models.Doctor.objects.all().filter(status=True),empty_label="Name and Department") it show me list but I would like use select2 in order to user redis and the search bar I would like create select and multiselect menu with searchbar to change list value: in the future I would like the same with table list and change a dropdown menu option if user insert a string in an input module or select an option from one other dropdown menu -
I got 'IncompleteSignature' issue in Aliexpress open platform
I am working over Django using python. I am working on the official SDK for python of Aliexpress. I am trying to get the ACCESS TOKEN from Aliexpress. I got 'IncompleteSignature' issue which means 'The request signature does not conform to platform standards as the part of the response body. Here is full results : {'error_response': {'type': 'ISV', 'code': 'IncompleteSignature', 'msg': 'The request signature does not conform to platform standards', 'request_id': '2141154c17373626146733360'}} My code is very simple because I referred the sample code of their site. (https://openservice.aliexpress.com/doc/api.htm#/api?cid=3&path=/auth/token/create&methodType=GET/POST) Here is my code: def callback_handler(request): code = request.GET.get('code') url = "https://api-sg.aliexpress.com/sync" appkey = "123456" appSecret = "1234567890XXXX" client = iop.IopClient( url, appkey, appSecret, ) request = iop.IopRequest('/auth/token/create') request.add_api_param('code', code) response = client.execute(request) response_type = response.type response_body = response.body print(response_type) print(response_body) return HttpResponse(f"Response type: {response_type}, Response body: {response_body}") I posted the question to the Aliexpress console but they replied with a very vague answer and a Java script reference code. I was shocked. It was not even python. And this advice can be only implemented if I modified their SDK itself. I am not sure if the python SDK is of practical working quality. Since I have been spending too much time and … -
How to Include a Message Field in Structlog Logs and Best Practices for ElasticSearch Integration
I'm working on a Django project where logging is critical, and I'm using structlog to format and manage logs. The plan is to send these logs to ElasticSearch. However, I've encountered an issue: the logs are missing the "message" field, even though I explicitly pass a message in the logger call. Here’s the log output I currently get: { "code": 200, "request": "POST /api/push-notifications/subscribe/", "event": "request_finished", "ip": "127.0.0.1", "request_id": "d0edd77d-d68b-49d8-9d0d-87ee6ff723bf", "user_id": "98c78a2d-57f1-4caa-8b2a-8f5c4e295f95", "timestamp": "2025-01-21T10:40:43.233334Z", "logger": "django_structlog.middlewares.request", "level": "info" } What I want is to include the "message" field, for example: { "code": 200, "request": "POST /api/push-notifications/subscribe/", "event": "request_finished", "ip": "127.0.0.1", "request_id": "d0edd77d-d68b-49d8-9d0d-87ee6ff723bf", "user_id": "98c78a2d-57f1-4caa-8b2a-8f5c4e295f95", "timestamp": "2025-01-21T10:40:43.233334Z", "logger": "django_structlog.middlewares.request", "level": "info", "message": "push notification subscribed successfully" } Here’s my current setup: settings.py Logger Configuration LOGGING = { 'version': 1, 'disable_existing_loggers': False, "formatters": { "json_formatter": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.JSONRenderer(), }, "plain_console": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.dev.ConsoleRenderer(), }, "key_value": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.KeyValueRenderer(key_order=['timestamp', 'level', 'event', 'message']), }, }, 'handlers': { "console": { "class": "logging.StreamHandler", "formatter": "plain_console", }, "json_file": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": "logs/ft_json.log", "formatter": "json_formatter", "maxBytes": 1024 * 1024 * 5, "backupCount": 3, }, "flat_line_file": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": "logs/flat_line.log", "formatter": "key_value", "maxBytes": 1024 * 1024 * …