Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: .filter() finds record but .get() with same query parameters does not
I am doing an ORM query using the .filter without the timeframe specified which returns two records. then I print those record column values to ensure I am not making any mismatches but then when I use the exact same values on the .GET method I get DoesNotExist error even though it just printed that record. Please verify if your comment is valid based on the printed statements before submitting stupid comments like: mAyBe yOu mAde A sPelLinG erRoR?! here is are the prints: Filter Query: timeframe=H4, symbol=XAUUSD, time=2024-04-10 14:00:00+00:00 Filter Record 2: XAUUSD, 2024-04-10 14:00:00, H4 GET Query: timeframe=H4, symbol=XAUUSD, time=2024-04-10 14:00:00+00:00 No record found. @csrf_exempt @require_http_methods(["POST"]) def get_label_data(request): data = json.loads(request.body) data = data.get('data') timestamp = data.get('timestamp') symbol_name = data.get('symbol') label_name_str = data.get('label_name') timeframe = data.get('timeframe') symbol = Symbol.objects.get(name=symbol_name) datetime_stamp = datetime.fromtimestamp(timestamp, tz=pytz.UTC) print(f"Filter Query: timeframe={timeframe}, symbol={symbol_name}, time={datetime_stamp}") forex_ohlc = ForexOHLC.objects.filter(symbol=symbol, time=datetime_stamp) forex_ohlc = list(forex_ohlc)[1] print(f"Filter Record 2: {forex_ohlc.symbol.name}, {forex_ohlc.time}, {timeframe}") print(f"GET Query: timeframe={timeframe}, symbol={symbol_name}, time={datetime_stamp}") try: forex_ohlc = ForexOHLC.objects.get(symbol=symbol, time=datetime_stamp, timeframe=timeframe) except ForexOHLC.DoesNotExist: print("No record found.") except ForexOHLC.MultipleObjectsReturned: print("Multiple records found.") except Exception as e: print(f"An unexpected error occurred: {e}") try: labels = TickLabel.objects.get(forex_ohlc=forex_ohlc, symbol=symbol, label_name__name=label_name_str) return JsonResponse({ 'label_name': labels.label_name.name, 'label_type': labels.label_type.name, 'hasLabel': True }) except TickLabel.DoesNotExist: … -
Exception Type: ValueError: node array from the pickle has an incompatible dtype
So I copied a DjangoML project from Github. The ML model is essentially a diagnosis system that predicts whether or not a patient is at risk based on the values of their blood tests. I'm running this project locally in VSCode but have yet to deploy the backend/ML model. I encountered this problem while attempting to forecast the outcome in the web browser. I'm using Python 3.11.0 for this project. The requirements.txt file includes: asgiref==3.5.0 Django==4.0.3 joblib==1.1.0 numpy~=1.26.4 pandas==2.2.2 python-dateutil==2.8.2 pytz==2022.1 scikit-learn==1.0.2 scipy==1.8.0 six==1.16.0 sklearn==0.0 sqlparse==0.4.2 threadpoolctl==3.1.0 tzdata==2021.5 `Traceback (most recent call last): File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django_MachineLearning_HealthcareApp-main\backend\views.py", line 76, in lpredictor result = ValuePredictor(llis, 7, mname) File "D:\Django_MachineLearning_HealthcareApp-main\backend\views.py", line 60, in ValuePredictor trained_model = joblib.load(rf'{mdname}_model.pkl') File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 658, in load obj = _unpickle(fobj, filename, mmap_mode) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 577, in _unpickle obj = unpickler.load() File "C:\Users\vanda\AppData\Local\Programs\Python\Python311\Lib\pickle.py", line 1213, in load dispatch[key[0]](self) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 402, in load_build Unpickler.load_build(self) File "C:\Users\vang\AppData\Local\Programs\Python\Python311\Lib\pickle.py", line 1718, in load_build setstate(state) File "sklearn\tree\_tree.pyx", line 865, in sklearn.tree._tree.Tree.setstate <source code not available> File "sklearn\tree\_tree.pyx", line 1571, in sklearn.tree._tree._check_node_ndarray <source code not available> Exception Type: ValueError at /diagnose/liver/report Exception … -
Wagtail: include custom form in SnippetsViewSet
I'am trying to include a custom form in the SnippetsView of one of my models.The form's purpose is to let the user upload a csv-file to add Data, the model in question has a one-to-many relationship with a second model, which is then bulk-updated with the data from the csv-file. Th goal is that for very view of every instance of the model generated via the SnippetViewSet the form can be found and used in a seperate Tab created via TabbedInterface. I can of course add manually a form via @hooks.register in a SubMenuItem or I can just add a new FileField to my model and add a hook or overide the models's save method, so that if the user uploads a file in the wagtail-admin it will get used to update the second model. I'd like rather to know wether there is a simple way to add a custom form to a SnippetView without having to subclass wagtail.snippets.views.snippets.EditView and CreateView and creating a new template or at least one not involving to much ducktaping. Currently I can upload the model via csv in the django-admin. But I'd like that to be possible in wagtail-admin as well. -
ModuleNotFoundError: No module named 'captcha.fields'
By Executing command python manage.py runserver in vscode terminal occured this error : Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner self.run() File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run self._target(*self._args, **self._kwargs) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ ...... File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "D:\<project path>\porsline\urls.py", line 10, in <module> path('', include('survey.urls')), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\urls\conf.py", line 39, in include urlconf_module = import_module(urlconf_module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "D:\<project path>\survey\urls.py", line 2, in <module> from . import views File "D:\<project path>\survey\views.py", line 14, in <module> from . forms import CreateSurveyForm, CreateQuestionForm, ShowSurveyForm File "D:\<project path>\survey\forms.py", line 11, in <module> from captcha.fields import CaptchaField ModuleNotFoundError: No module named 'captcha.fields' … -
How to properly use javascript within oTree / django?
I have a problem regarding implementing my non-oTree HTML, CSS, JS files into oTree format. I have this puzzle game (see screenshot 1) . Implemented in oTree it is buggy - as you can see in screenshot 2 . The JS logic kinda works as the counter recognises clicks on the here empty and buggy structured picture pieces. The JS code lies within the PuzzelPage.html file like this {{ block scripts }} <script> var turns = 0; // Zähler für die Anzahl der Züge var puzzleSolved = false; // Zustand des Puzzles var timer; // Globale Variable für den Timer var currTile, otherTile; // Variablen für die aktuellen Puzzle-Teile // Diese Funktion mischt ein Array in einer zufälligen Reihenfolge function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } // Diese Funktion wird aufgerufen, sobald das Fenster geladen ist window.onload = function() { let imgOrder = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; shuffleArray(imgOrder); // Erstelle die Puzzle-Teile und füge sie zum Board hinzu for (let r = 0; r < 3; r++) { for … -
Setting Timezone for django connection
The Problem: Postgresql timezone is set to 'UTC' /etc/postgresql/15/main/conf.d/local.conf: log_timezone = Europe/Warsaw timezone = UTC database has been altered: ALTER DATABASE example_database SET TIMEZONE TO 'Europe/Warsaw'; Postgresql user has set own time_zone SELECT rolconfig FROM pg_roles WHERE rolname = 'someuser'; {TimeZone=Europe/Warsaw} settings.py USE_TZ = True TIME_ZONE = 'Europe/Warsaw' but during connection postgresql is getting: LOG: statement: SELECT set_config('TimeZone', 'UTC', false) What am I doing wrong??? -
Trying to connect oracle db to the django application using wallet.zip file
I'm configuring my Oracle database to the django application using wallet.zip file in the following way. Note: This wallet.zip file contains tnsnames.ora file. In settings.py file: DATABASES = { "oracledb": { "ENGINE": "django.db.backends.oracle", "NAME": "dummyemployee", "USER": "dummyuser123", "PASSWORD": "dummypass123", "OPTIONS": { "wallet_location": "C:\\Users\\Administrator\\Desktop\\Wallet_Location" } } } But when I try to execute the API. It's returning the following error: "wallet_location is an invalid keyword argument for this function" -
Persist list inside a object Django Rest Framework
I'm trying to persiste list of a python object (dico) like this but it's difficult { "leader": { "nameLastname": "AAAAA" }, "employeeRemun": { "grossSalaryBase": 111, "bonuses": 222, "travellingExpenses": 333, "noRemuneration": false }, "abandonmentCurrentAccount": { "abandonDate": "2023-10-20", "partner": "BBB", "amount": 444, "recoveryDate": "2023-10-04", "recoveryAmount": 5555, "abortTime": "-16 jours" }, "commentReviewDuring": { "review": "COMMENT DURING" }, "commentReviewAfter": { "review": "COMMENT AFTER" }, "list_benefits": [ { "natureAvantage": { "actualAmount": 42354, "previousAmount": 53234 }, "leaderAvantage": { "nameLastname": "AAAAA" }, "typeAvantage": { "benefitType": "Private Jet" } }, { "natureAvantage": { "actualAmount": 43532, "previousAmount": 4324 }, "leaderAvantage": { "nameLastname": "AAAAA" }, "typeAvantage": { "benefitType": "Rolls Royce" } } ] } Patch Methode: At beginning i try to do this but i don't find how to access index of list ('HERE') : I try to acces element inside the request with request.data.get(...) but for the natureAvantage it's not a {} but a [] need to be acces by a index for indexLls in llsByIdSerialized.data['naturalBenefits']: benefitTypeById = AvantageNatureDirigeant.objects.get(id=indexLls) benefitRefresh = LeaderBenefeitTypeSerilizer(instance=benefitTypeById, data=request.data.get('remSection', {}).get('list_benefits', {}).get('natureAvantage', {})) if benefitRefresh.is_valid(): benefitRefresh.save() So i try to do this one : Create a seperated object for index, benefit_data in enumerate(request.data.get('remSection', {}).get('list_benefits', [])): actual_amount = benefit_data.get('natureAvantage', {}).get('actualAmount') previous_amount = benefit_data.get('natureAvantage', {}).get('previousAmount') data_to_serialize = { … -
Fetching Data from a .sql file in a Django Project
I have a django project. I have a dump of the data from a Mysql database in a .sql file and want to query some data from this file into my django project and display it. I am fairly new to django. Need some help My settings.py looks like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', } } -
DLL load failed while importing _rust: The specified procedure could not be found
I am trying to hit an API that is of POST type, it generates access and refresh tokens which can be used to access other APIs. It takes the username and password in the body, which we generate while creating a superuser (admin) in Django. This is the detailed error I'm encountering while hitting the API in Postman: Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.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\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework_simplejwt\views.py", line 44, in post serializer.is_valid(raise_exception=True) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\serializers.py", line 223, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\serializers.py", line 445, in run_validation value = self.validate(value) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework_simplejwt\serializers.py", line 77, in validate data["refresh"] = str(refresh) File … -
How can I fix my blacklist token at Django rest framework simple JWT? Error: Given token not valid for any token type"
Im using rest framework simple_jwt to login, everything works to register, login im having the access and refresh token. When I check on the website of JWT Web tokens, It says that the token has type "refresh", the same that I should pass to the Bearer Authorization on postman. But I'm facing this error if the fresh token after login that im passing: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token has wrong type" } ] } My code: LogoutSerializer: class LogoutUserSerializer(serializers.Serializer): refresh_token = serializers.CharField() default_error_message = {"bad_token": ("Token is invalid or has expired")} def validate(self, attrs): self.token = attrs.get("refresh_token") # Corrected accessing the attribute try: # Ensure the token is not empty if not self.token: raise serializers.ValidationError("Token is required") # Check if the token is valid token = RefreshToken(self.token) # Ensure the token is a refresh token if token.token_type != "refresh": raise serializers.ValidationError( "Given token not valid for refresh token type" ) except TokenError: raise serializers.ValidationError("Token is invalid or has expired") return attrs def save(self, **kwargs): try: token = RefreshToken(self.token) token.blacklist() except TokenError: return self.fail("bad_token") LogoutView: class LogoutUserView(GenericAPIView): serializer_class = LogoutUserSerializer permission_classes = [IsAuthenticated] def post(self, … -
`I am trying to build a registration form in Django, using Django form
i put {{form.username}} {{ form.email }} {{ form.password }} in my html code instead of text boxes and i can't see them, i also made a forms.py file and views.py this is register.html `{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Registration</title> <link rel="stylesheet" href="{% static "register.css" %}"> </head> <body> <div class="container"> <h2>User Registration</h2> <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Username:</label> {{form.username}} </div> <div class="form-group"> <label for="email">Email:</label> {{ form.email }} </div> <div class="form-group"> <label for="password">Password:</label> {{ form.password }} </div> <div class="form-group"> <button type="submit">Register</button> </div> </form> </div> </body> </html>` this is forms.py `from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CreateUserForm(UserCreationForm): class Meta: model = User fields =[ 'username', 'email', 'password']` this is views.py `def register(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return render(request, 'register.html')` I tried debugging, wathing a tutorial and asking chat gpt and i couldn't fix it -
Django guest user cart functionality? Is it safe?
Creating an e-commerce website project to try and learn Django and more about Javascript, so I have been going over a tutorial for the past week. In the tutorial, there is a guest user cart feature. It works by storing user and product data into the cookies. Though, I am having trouble getting it to add multiple of the same item. If I were to login as a user the website works fine. The remove feature works fine for deleting an item out of the cart as guest. In the JavaScript console, the items in the cart get deleted, but the cookies retain the same information before the website reloads. Don't know the cause for this issue. I would really like this feature to work out. JavaScript Console Log cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function() { //sets variable to add to the dictionary. var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) //checks to see if the user is logged in. console.log('USER:', user) if (user === 'AnonymousUser') { addCookieItem(productId, action) } else { updateUserOrder(productId, action) } }) } function addCookieItem(productId, action) { console.log('Not logged in.') //add quantity … -
TokenObtainPairSerializer override
i'am using django-otp and Django-rest-jwt my goal is I want to check if user has enable 2fa if yes I will give him the refresh and access token i would like to change my top file to not required . class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['otp'] = OtpField() def validate(self, attrs: Dict[str, Any]) -> Dict[str, str]: data = super().validate(attrs) user_logged_in.send(sender=self.user.__class__,request=self.context['request'],user=self.user) if self.user is None: user_login_failed.send(sender=self.user.__class__,request=self.context['request'],user=self.user) return data -
Deployed Django Application on PythonAnywhere: Connection Refused Error When Controlling Raspberry Pi Robot Remotely
I am trying to deploy a Django web application on PythonAnywhere that controls a Raspberry Pi robot remotely. The application worked flawlessly locally using ngrok to establish a connection, but after deploying it to PythonAnywhere, I encountered the following error: 2024-04-17 07:49:53 Connection refused: The server is not accepting connections. I tried: Added localhost to the ALLOWED_HOSTS in Django settings. Tried running the server on a different port. Disabled the firewall on the Raspberry Pi. Added corsheaders to the Django project. -
Foreign Key dropdown in Admin returns __str__, can I change it so some other column? [duplicate]
Here is my setup: # myapp.models class Country(models.Model): alpha2 = models.CharField(primary_key=True, max_length=2), name = models.CharField(max_length=64, def __str__(self): return "%(alpha2)s %(name)s" % {"alpha2": self.alpha2, "name", self.name} class Address(models.Model): id = models.BigAutoField(primary_key=True) province = models.CharField(max_length=64) country = models.ForeignKey(Country, on_delete=models.PROTECT) # myapp.admin from django.contrib import admin from .models import Address, Country admin.site.register(Address) admin.site.register(Country) When I go to http://localhost:8000/admin, and go to add a new Address, the country dropdown shows the output of Country().__str__ (i.e. IN India). I have 2 questions: I believe I would be able to choose what I want to show in the dropdown if I was writing my own form (without changing __str__). Is this correct? Can I change what I want to show in admin panel without changing __str__? -
Django project not fetching static files
I am developing a small app for my course in Django. Now, I am trying to bring my project to a cloud system, in this case using Heroku, however it seems that I have an issue with fetching my static files when running the collectstatic command. I get the following error: Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "/Users/mlopez/journal_project/manage.py", line 22, in <module> main() File "/Users/mlopez/journal_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect handler(path, prefixed_path, storage) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 368, in copy_file if not self.delete_file(path, prefixed_path, source_storage): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 278, in delete_file if self.storage.exists(prefixed_path): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/files/storage/filesystem.py", line 165, in exists return os.path.lexists(self.path(name)) ^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/storage.py", line 39, in path raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Here are my settings.py: import os from pathlib import Path # Build paths inside the … -
Python Django ASGI - saving image to a model with django-storages to S3 bucket results in memory leak
First of all I've been looking for a solution for a couple of days and tried various code snippets found here. The problem: hosted web app consumes more and more memory everytime image is saved to a Django model ImageField set up with S3 via django-storages. What I tried or observed: no matter which ASGI server I used, result was the same (Daphne, Uvicorn, Hypercorn, Granian). I checked memory allocation line by line in cricital places with tracemalloc and the memory consumption rised specifically after saving images. async def upload_image(content_img, content_thumbnail): lf1 = tempfile.NamedTemporaryFile() for chunk in content_img.chunks(): lf1.write(chunk) lf2 = tempfile.NamedTemporaryFile() for chunk in content_thumbnail.chunks(): lf2.write(chunk) uploaded_image = await UploadedImage.objects.acreate(user=request.user, type=type, app_name=app_name) def upload_image_sync(): uploaded_image.image.save(content_img.name, lf1) uploaded_image.thumbnail.save(content_thumbnail.name, lf2) await sync_to_async(upload_image_sync)() In above code invoking 'uploaded_image.image.save' or 'uploaded_image.thumbnail.save' shows higher memory usage with tracemalloc, pointing 'json/decoder.py' as the file which occupies memory. And here's the interesting part. Saving image to model shows ~10MB more memory used and jumps from ~45MB to ~55MB. If I save lots of images in short period of time, I saw spikes up to ~400MB, but after that the current usage lowered and it looked like memory was released. Not always going back to 45MB but … -
Django admin site not loading in localhost
I am running python manage.py runserver on my django project but my django admin site is not loading locally. All the other urls apart from http://127.0.0.1:8000/ are functional. I am using Django==4.2.11 and Python 3.9 This is my urls.py from django.contrib import admin --- from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(("api.urls", "api"), namespace="v1")), ] and my settings.py ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "api", "authentication", ] MIDDLEWARE = [ "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", "django.middleware.clickjacking.XFrameOptionsMiddleware", "simple_history.middleware.HistoryRequestMiddleware", ] SITE_ID = 1 I don't know where else to look. -
how to show embeded video on home page from blog page in wagtail?
As shown i can embed the video via URL. but it save videos as url and text as whole body. i an unable to extract videos only and show in home page. https://docs.wagtail.org/en/v4.0.3/editor_manual/new_pages/inserting_videos.html# i tried using from wagtail.core.rich_text import RichText register = template.Library() @register.filter(name='extract_videos') def extract_videos(body): videos = [] # Check if the body content is RichText if isinstance(body, RichText): # Iterate through each block in the RichText for block in body: # Check if the block is of type 'embed' if block.block_type == 'embed': # Append the value (which should be the embedded video URL) to the videos list videos.append(block.value) return videos -
Django filter objects using two fields
I have a Django model looks like this class Product(models.Model): product_type_id = models.IntegerField() product_sub_id = models.IntegerField() ... Where a product can be defined as name product_type_id product_sub_id toy cars 13 8 toy planes 13 11 cheese 2 1 bread 2 4 chocolate cake 2 8 With a list of (product_type_id, product_sub_id), is there an easy way to filter out products rather than pulling all matched objects and compare them with the list afterwards? For example I have [(13, 8), (2, 1)] for retrieving product "toy cars" and "cheese" My current solution is my_list = [(13, 8), (2, 1)] filtered_products = Products.objects.filter( product_type_id__in = [i[0] for i in my_list], product_sub_id__in = [i[1] for i in my_list] ) matching_products = [p for p in filtered_products if (p.product_type_id, product_sub_id) in my_list] -
Why Django Admin static doesn't work in nginx and docker?
The problem is when I make docker-compose up and enter my website at localhost/admin in ngnix I don't see the default django admin styles. nginx.conf location /static/ { autoindex on; alias movies_admin/staticfiles/; } components/static.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = 'movies_admin/staticfiles/' docker-compose.yml version: '3.8' services: django: build: context: . volumes: - "./movies_admin:/movies_admin" - "./movies_admin:/movies_admin/staticfiles/" environment: - DB_HOST=database - DB_NAME=movies_database - DB_USER=app - DB_PASSWORD=123qwe - SECRET_KEY='django-insecure-8h%wg+drqmqjkw$8wm7#)#%*fb3b%(-e!-kbdth^#9u)23u!48' command: sh -c "uwsgi --ini /movies_admin/uwsgi.ini" depends_on: - database database: image: postgres:16 environment: - DB_NAME=movies_database - DB_USER=app - DB_PASSWORD=123qwe volumes: - $HOME/postgresql/data:/var/lib/postgresql/data nginx: image: nginx:latest volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./movies_admin:/movies_admin/staticfiles/ ports: - "80:80" depends_on: - django Dockerfile FROM python:3.10.0-alpine RUN apk add postgresql-client build-base postgresql-dev linux-headers pcre-dev WORKDIR /movies_admin COPY requirements.txt . RUN pip install -r requirements.txt --no-cache-dir EXPOSE 8000 COPY movies_admin . RUN python3 manage.py collectstatic --no-input I read all available tutorials and understand the algorithm: Setup staticfiles in settings.py In Dockerfile collectstatic Mount staticfile path in nginx and django containers volumes Pass the path to the staticfiles in nginx.conf to setup routing if static was requested Despite all this I don't see the styles in django admin. What might … -
Django merge two m2m_change signals
i have a post model which has category m2m field and tag m2m field, on post post_save i want to retrieve the category ids and tag ids from that post model instance, but after some research i found out, m2m fields arnt save at that time and i want to use m2m_changed signal, but since i have two m2m fields, how can i merge two signals or in posts post_save is there a way to wait for the creation of m2m fields, or do i have to create custom signal class Category(models.Model): description = RichTextField(null=True, max_length=10000) name = models.CharField(max_length=300, null=False, blank=False) slug = models.CharField(max_length=400, null=True, blank=True, unique=True) parent = models.ForeignKey("Category", on_delete=models.CASCADE, null=True, blank=True) # readonly fields wp_category_id = models.CharField(max_length=10, null=False, editable=False) total_posts = models.CharField(max_length=10, null=True, editable=False) category_link = models.CharField(max_length=600, null=True, editable=False) def __str__(self) -> str: return f"{self.name}" class Meta: verbose_name_plural = "Categories" class Tags(models.Model): description = RichTextField(null=True, max_length=10000) name = models.CharField(max_length=300, null=False, blank=False) slug = models.CharField(max_length=400, null=True, unique=True, blank=True) # readonly fields wp_tag_id = models.CharField(null=False, editable=False, max_length=10) tag_link = models.CharField(null=True, editable=False, max_length=400) def __str__(self) -> str: return f"{self.name}" class Meta: verbose_name_plural = "Tags" class Posts(models.Model): wp_post_id = models.CharField(max_length=200, null=True, editable=False) slug = models.CharField(max_length=1000, null=True, unique=True, blank=True) status = models.CharField(choices=status_choices, max_length=200) … -
How can celery use Django ORM?
How can celery use Django ORM? Celery and django are diffent processes. But, Celery worker can use Django Application code.(ORM, Model..) I think celery process have django application code. Is it right? What should I do setting when django and celery on another server physically? I was wondering how Celery can use the code in the django. -
How to make href point to a django template and pass context to it?
I have a django template listing mails/messages from a sql database. I am trying to make those messages clickable by using an <a> tag, as to open a page displaying the content of the message. Part of my template listing the messages : <table> <th>ID</th> <th>DATE</th> <th>SUJET</th> <th>SENDER</th> {% for message in messages %} <tr> <td>{{message.id}}</td> <td>{{message.date}}</td> <td><a href="">{{message.subject}}</a></td> <td>{{message.sender.address}}</td> </tr> {% endfor %} </table> Is there a way to fill this href such that it calls a views.py function while passing it the correct message instance ? I tried to write <a href={% url 'show_message' {{message}} %}> Where show_message would be a url name in my app_urls.py, but it doesn't seem to work. The doc seems to point to something similar though. Thank you !