Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: using two related fields / foreign keys at once
I have three models: class Team(models.Model): team_id = models.AutoField() team_name = models.CharField() class Game(models.Model): game_id = models.AutoField() home_team = models.ForeignKey(Team, on_delete=models.CASCADE) away_team = models.ForeignKey(Team, on_delete=models.CASCADE) class TeamBoxScore(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='game_boxscore') team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team_boxscore') # some stats here What I want to do is, for every Game instance, access the TeamBoxScore that matches both the Game instance and the Team instance referenced by home_team/away_team. Is there a way that I can have game.home_team.team_boxscore reference only the boxscore for that game_id? Or, conversely, can I specify which game.game_boxscore I want to return (the one that matches home_team or the one that matches away_team)? I want to minimize queries and avoid long iterative solutions. I've tried annotating the fields from each TeamBoxScore instance to every Game (referencing the game_boxscore related field), but that ends up doubling the size of the queryset and placing the values from the home boxscore and the away boxscore in separate instances. I've tried going through the team_boxscore related field, but that returns every boxscore for that team (game.home_team.team_boxscore). I've further tried to groupby these annotated values and just return the sum, but this is both inelegant and takes too long (and could be wrong!) … -
Django believes that there is a "SuspiciousFileOperation". This is not true
Django has a belief that there is a SuspiciousFileOperation error when this just is not the case. My fully reproducible setup is below. It continues to return this error despite the fact that: I have installed and set up Whitenoise correctly, as well as in the Middleware and InstalledApps, in the settings.py filw, as well as the following: INSTALLED_APPS = [ 'django.contrib.staticfiles', ] MIDDLEWARE = [ "whitenoise.middleware.WhiteNoiseMiddleware", ] STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_URL = 'static' STATICFILES_DIRS = [ BASE_DIR / "static" ] Despite the fact that I have correctly set up the static config in my root urls.py folder, as follows: from django.conf import settings from django.conf.urls.static import static from django.views.static import serve urlpatterns = [ ...... ] # Only for development. Do not use this in production. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My directory is as follows: <PROJECTNAME> <ROOTFOLDER> settings.py urls.py <APP NAME> static file.css static libraries css image-video-hero.css staticfiles libraries css image-video-hero.css Therefore, there is no reason as to why Django should have an issue with this, however, when I run the command of python manage.py collectstatic command, I still get the trace back of: File "<FILEPATH>\<PROJECTNAME>\.venv\Lib\site-packages\django\utils\_os.py", line 31, in safe_join raise … -
Django, exists subquery always returns False
I faced an issue, that my subquery returns False, even it should return True. from wagtail.models import WorkflowState, Page, Workflow import pytest def test_filter_pages(user): page = PageFactory.create( owner=user, live=False, latest_revision_created_at=timezone.now(), ) WorkflowState.objects.create( content_type=ContentType.objects.get_for_model(Article), base_content_type=ContentType.objects.get_for_model(Page), object_id=str(page.pk), workflow=Workflow.objects.get(name="Moderators approval"), status=WorkflowState.STATUS_IN_PROGRESS, requested_by=user, ) workflow_states = WorkflowState.objects.filter( status=WorkflowState.STATUS_IN_PROGRESS, object_id=str(OuterRef("pk")) ) queryset = ( Page.objects.select_related("owner", "latest_revision") .annotate(workflow_state_status=Exists(workflow_states)) .filter(owner=user) ) lists_ids = [ page.id for page in queryset if page.workflow_state_status ] assert lists_ids != 0 In this test there is only one page, which should have workflow state. But test fails with list_ids = 0. What is wrong here? Moreover, when I try to replace workflow_state_status with simple WorkflowState.objects.filter( object_id=self.pk, status=WorkflowState.STATUS_IN_PROGRESS, ).exists() everything works correct (except database queries) -
Django stopped updating static files
Django does not upload static files Hey guys, I am head to you because I have a problem I can’t fix. I am on localhost and Django does not apply modifications I have made on static files, although the file is changed. So to start here what I have done so far: clearing browsers caches rebooting the server step 1&2 of best answer: stackoverflow.com/questions/27911070/django-wont-refresh-staticfiles changing browser deleting pycache files Nothing seems to work, if you had an explanation on how to fix this but mostly WHY this happens, would be so nice ! 😊 -
DJANGO Compute number of hours the user spend per day
I have Clocking table in database. I wanted to count the users' time spend per day. For example 2024-03-21, user 1 spend 6.8 hours, the next day he spend n number of hours and so on (['6.8', 'n', ... 'n']) user date timein timeout 1 2024-03-21 10:42 AM 12:00 PM 1 2024-03-21 01:10 PM 06:00 PM 1 2024-03-22 01:00 PM 05:47 PM ... ... ... ... This is my models.py class EntryMonitoring(models.Model): user = models.ForeignKey('User', models.DO_NOTHING) timein = models.CharField(max_length=15, blank=True, null=True) timeout = models.CharField(max_length=15, blank=True, null=True) date = models.DateField(null=False) I wanted to get the list of hours spend per day, that would be really useful for me in plotting charts. Thank you in advance! -
How to restart gunicorn when used with config file
I am using gunicorn to server a django application. I am using a config file and starting gunicorn using the command gunicorn -c config/gunicorn/dev.py I want to know how to restart gunicorn. i am not able to use sudo systemctl restart gunicorn command which gives the below message: Failed to restart gunicorn.service: Unit gunicorn.service not found. I am very sure that gunicorn is running as i am able to use the application on the web. What is the way to restart gunicorn in this case. Below is the config file of gunicorn: # Django WSGI application path in pattern MODULE_NAME:VARIABLE_NAME wsgi_app = "someapp.wsgi:application" # The granularity of Error log outputs loglevel = "debug" # The number of worker processes for handling requests workers = 2 # The socket to bind bind = "0.0.0.0:8000" # Restart workers when code changes (development only!) reload = True # Write access and error info to /var/log accesslog = errorlog = "/var/log/gunicorn/dev.log" # Redirect stdout/stderr to log file capture_output = True # PID file so you can easily fetch process ID pidfile = "/var/run/gunicorn/dev.pid" # Daemonize the Gunicorn process (detach & enter background) daemon = True -
Python code to connect to FTP /convert my code in way that it uses FTP instead of SFTP
please help to write code to connect ftp using python download fresh files from specfic directory load those file in Mysql database ,mark them processed after downloading file from ftp ,after loading them into mysql database If any one can provide python script for this -
What are the key technologies and concepts involved in backend web development? [closed]
Key Technologies: Programming Languages: Backend development can be done using various languages, such as: Node.js: JavaScript runtime built on Chrome's V8 engine, popular for its non-blocking, event-driven architecture. Python: Known for its simplicity and readability, often used with frameworks like Django and Flask. Java: Offers platform independence and is commonly used in enterprise applications. Frameworks: Frameworks provide a structured way to build web applications. Some popular backend frameworks include: Express.js (Node.js): Minimalistic and flexible, ideal for building APIs and web apps. Django (Python): High-level framework for rapid development, follows the DRY (Don't Repeat Yourself) principle. Spring (Java): Comprehensive framework for Java, offering features like dependency injection and MVC architecture. Databases: Backend development involves interacting with databases to store and retrieve data. Common databases include: SQL Databases: Such as MySQL, PostgreSQL, and SQLite, used for structured data. NoSQL Databases: Such as MongoDB and Cassandra, used for unstructured or semi-structured data. Key Concepts: RESTful APIs: Representational State Transfer (REST) is a design pattern for creating scalable web services, commonly used in backend development. Authentication and Authorization: Implementing secure user authentication and authorization mechanisms to protect backend resources. Server-Side Rendering (SSR) vs. Client-Side Rendering (CSR): Understanding the difference between rendering techniques and when … -
Is it possible to add a "InputField" in ChoiceField in Django?
I'm in the process of developing a form that aligns with a database model. One of the fields in this form requires users to select from a range of options. Initially, I implemented this using Django's ChoiceField. However, I'm exploring the possibility of allowing users to input their own option if it's not available in the predefined choices. Is there a way to integrate this? -
Django htmx not targeting assigned element
I have a django-tables2 template that I've modified to assign a unique row id to each row. I'm trying to add a button that will allow a user to delete a given row on a click. I'm using htmx to initiate the deletion request. I also have an htmx enabled edit button that is working as intended regarding sever side modifications and updating the DOM. The delete button behaviour is as expected on the server side, but the swap appears to impact only the button, and not the tag. After clicking the delete button, the record is removed from the database, but only the button disappears on the DOM, not the <tr>. I won't include the views.py as it's fairly straightforward in that it retrieves the appropriate record, executes the delete, and returns an empty HTTPResponse. I've tried adding an hx-target with an hx-swap, but this deactivates any htmx call capability on the button. I've also tried putting a <div> wrapper around the <tr> and targeted that with my oob swap with no luck. Here is the table.tbody template with both the edit and the delete buttons: {% extends 'tablestyle.html' %} {% load humanize %} {% block table.tbody %} <tbody … -
django model save operation not creating on default database
I have two databases defined: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_offshore_bkup' }, 'onshore_db': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_onshore_bkup' } In the model: def save(self, *args, **kwargs): kwargs['using'] = 'default' super().save(*args, **kwargs) NoTice I've commented these #kwargs['using'] = 'onshore_db' #super().save(*args, **kwargs) In the viewset: with transaction.atomic(): self.serializer_class = self.create_serializer_class created_user = viewsets.ModelViewSet.create(self, request, *args, **kwargs) created_user_id = created_user.data['id'] The create() only saves the record in onshore_db immediately and doesn't consider the default db. Even after commenting the onshore_db configuration, when I run the app, I find that the new model objects are created in onshore_db only and no records in default db. What could be the reason? There's also a db-router defined: def get_db_name(): cache_data = {} db = 'default' request = get_current_request() try: user_id = request.session._session_cache['_auth_user_id'] cache_data = cache.get(user_id, {}) except Exception as e: return db if cache_data.get('CLIENT_DB_NAME', None): db = cache_data.get('CLIENT_DB_NAME') return db class MatrixDBRouter: # TODO encrypt db name where data from onshore def db_for_read(self, model, **hints): return get_db_name() def db_for_write(self, model, **hints): return get_db_name() def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True But this only returns the default … -
How do we update pip to it's latest version
A new release of pip is available: 23.2.1 -> 24.0 [notice] To update, run: python.exe -m pip install --upgrade pip By running provided command i am unable to update pip to it's latest version. it's showing the following error upon running the command " python.exe -m pip install --upgrade pip" ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Python311\Lib\site-packages\pip\init.py' Consider using the --user option or check the permissions. please help to solve the above mentioned problem -
The same uuid is generated for different objects in Django
When I run server on localhost I am able to add new objects in my postgre database through Django admin panel, but only one for every table. When I try to add second new object, it assigns the same uuid that has already been used. There is an example of model with uuid as primary key: models.py from django.db import models from authuser.models import User from django.utils import timezone import uuid class Thread(models.Model): idthread = models.UUIDField(default=uuid.uuid4(), primary_key=True, unique=True) date_created = models.DateTimeField(default=timezone.now) userid = models.ForeignKey(User, on_delete=models.DO_NOTHING) name = models.CharField() def __str__(self): return self.name Only after restarting the server it will assign new unique uuid to object that I would like to add. -
How to implement dual authentication (email and phone number) in Django Rest Framework?
I'm building a Django Rest Framework (DRF) application and I need to implement dual authentication, allowing users to sign in using either their email or mobile number. What is the best approach to implement this? I've already set up the authentication system using email, but now I need to extend it to support mobile number authentication as well. Should I create a custom authentication backend, or is there a DRF package that can help me achieve this more easily? I'd appreciate any advice or examples on how to implement dual authentication in DRF. Thank you! -
ModuleNotFoundError: No module named 'psycopg2' while makemigrations on postgres DB
I cloned a github project on Django and i was following the instructions to execute the program. I am new so, i went ahead and downloaded postgres and installed it. at the make migrations step, this error was logged along with bunch of paths :- ModuleNotFoundError: No module named 'psycopg2' i was following the steps given in the documentation file for this which are as follows : " Installing the Postgres and enabling it in the background We will go to telusko\settings.py in the project folder Around line 78, there's DATABASES dictionary, we will set the value for keys ('NAME', 'USER' & 'PASSWORD') to 'postgres' Then we'll execute python3 manage.py makemigrations & python3 manage.py migrate Finally, we will run the project by python3 manage.py runserver " i followed the steps, at the 3rd step, instead of 'postgre' as the password, i typed in the password asked at the installation process BUT at the 4th step when i run the python3 manage.py makemigrations this error is shown: ModuleNotFoundError: No module named 'psycopg2' i want this project somehow working till tomorrow so please help -
How to Submit Separate Actions from a Single Form Tag? (Django)
I have written the following code where a submit action with the value {{category.name}} unexpectedly triggers the "create" button in form_category, resulting in a "Please enter a name" message. This approach worked fine in a previous project using the same logic. I've confirmed that the urls.py is properly set up. What could be the issue? <form method="POST"> {% csrf_token %} category name: {{ form_category }} <input type="submit" value="create" formaction="{% url 'mk_category' %}"> <span> | </span> {% for category in categories %} <input type="submit" value="{{category.name}}" formaction="{% url 'index_with_category' category.id %}"> {% endfor %} </form> Thank you very much for your help! Wrapping each submit button in separate form tags resolves the issue. However, I plan to continue using multiple submit buttons within a single form in the future. I have checked urls.py multiple times and found no issues. Please help me with this. -
Django Python - How to Query this
I have this Consumer model class ConsumerModel(models.Model): GENDER_LIST = ( ('male','MALE'), ('female','FEMALE'), ("lgbt",'LGBT') ) REGISTER_AS = ( ('consumer','CONSUMER'), ('manager','MANAGER') ) uid = models.CharField(max_length=8) # remove the default value some time profile_id = models.UUIDField() user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=40) birthdate = models.DateField(null=True,blank=True) mobile_number = models.CharField(max_length=12, null=True, blank=True) gender = models.CharField(max_length=20,choices=GENDER_LIST,null=True,blank=True) profile_image = models.ImageField(null=True,blank=True,upload_to="images/") register_as = models.CharField(null=True, blank=False,choices=REGISTER_AS, max_length=12) def __str__(self): return self.user I have this view where I want to look/print for the Consumer with the following user but it returns and error: serializer = ConsumerLoginSerializer(data=request_data) if serializer.is_valid: try: user = User.objects.get(email=request_data["email"]) except: return Response(data={'status': wrong_input, 'message':wrong_body_vals_msg, 'errors':{"Email":"User not found"}}) print("PROFILE ID: " + ConsumerModel.objects.get(user=user)) return Response(data={"status": ok, 'message': "Success"}, status=ok) -
Embedded react component disable select text on other html elements
I am trying to include a react component in a django template which contains non-react content. My template contains the following code: {% load static %} <!DOCTYPE html> <html> <body> <h1>This text CAN NOT be selected</h1> <h2>React app</h2> <div id="react1"></div> <!-- this is the component that the react component will live in. --> <script src="{% static js %}" defer></script> <!-- js is a variable pointing to the main.XXXXX.js file. --> </body> </html> The variable js refers to the build/static/js/main.XXXXX.js-file build using npm run build and served using django. The index.js file (in react) simply add a component to the div: import React from 'react'; import { createRoot } from 'react-dom/client'; import App2 from './App2'; if(document.getElementById("react1") != null){ const root = createRoot(document.getElementById('react1')); root.render( <App2 /> ); } The component (App2.js) is a very simple hello-world example. The page renders correctly (the app is a simple counter app) as shown in the screenshot so all files are up-to-date. As can be seen I can select/interact with the application, but I cannot select the text defined in the tag (and more importantly, events such as button clicks outside of react are not triggered etc.). The React counter-app works as expected. I have googled … -
Cannot index models from Django to Elasticsearch
I have a Django project where we're going to use Elasticsearch for a full-text search. I have a task to connect it with the existing Django project. The first thing I found django-elasticsearch-dsl package. I did everything like in tutorial and all worked fine, but the idea was in using elasticsearch-dsl. I don't understand how to create indexes right now. If in django-elasticsearch-dsl the only thing I need is to run python3 manage.py search_index --rebuild inside Django container, but here I have no idea. I store all code in documents.py. documents.py from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Document, Text connections.create_connection(hosts=['http://elasticsearch:9200']) class FilmWorkDocument(Document): title = Text() description = Text() class Index: name = 'film' FilmWorkDocument.init() first = FilmWorkDocument(title='Example1', description='Example description') first.meta.id = 47 first.save() docker-compose.yml elasticsearch: image: elasticsearch:8.13.0 container_name: elasticsearch environment: - "ES_JAVA_OPTS=-Xms200m -Xmx200m" - discovery.type=single-node - xpack.security.enabled=false ports: - 9200:9200 Sending a request http://localhost:9200 shows that everything is ok. { "name" : "eeb958274241", "cluster_name" : "docker-cluster", "cluster_uuid" : "wUQjIKoLTNGKtFH7A1tzSw", "version" : { "number" : "8.13.0", "build_flavor" : "default", "build_type" : "docker", "build_hash" : "09df99393193b2c53d92899662a8b8b3c55b45cd", "build_date" : "2024-03-22T03:35:46.757803203Z", "build_snapshot" : false, "lucene_version" : "9.10.0", "minimum_wire_compatibility_version" : "7.17.0", "minimum_index_compatibility_version" : "7.0.0" }, "tagline" : "You Know, for Search" } But after … -
Django works perfectly on a local machine, but doesn't work in production
Django works perfectly on a local machine, but has errors with Postgres in production (I am using the same postgres DB in prod and locally). Django server hosted on Railway gives me this: Settings (WORKS PERFECTLY ON A LOCAL MACHINE WITH THIS IN-PROD DATABASE AND SAVES DATA): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } DATABASE_URL = os.getenv('DATABASE_URL') .env: DATABASE_PRIVATE_URL={{DATABASE_PRIVATE_URL}} DATABASE_URL={{DATABASE_URL}} DB_HOST=viaduct.proxy.rlwy.net DB_NAME=railway DB_PASSWORD={{DB_PASSWORD}} DB_PORT=19232 DB_USER=postgres SECRET_KEY={{SECRET_KEY}} Proof for local server working: Postgres server logs (local machine): -
que aplicaciones desplegar en heroku
el problema es que tengo una aplicacion en python y django que usa conexiones web socket con cnannels y daphne, el asunto es si heroku permite el uso de estas conexiones ya adquiri una suscripcion en pythonAnywhere y me toca cancelarla porque no admiten estas conexiones y me vine a dar cuenta ya con los errores que arrojaba despues de estar en el servidor. si, si se permite este tipo d conexion en heroku quiciera que me dieran un enlace donde expliquen bien como se configuran en esete servidor heroku y si no entoces que proveedor de servicios puedo contratar para el uso de esta aplicacion, recuerden aplicacion desarrollada en django y python con conexiones websocket usando chanels y daphne con BD mysql probe en pyrhonAnywhere y quede viendo un chispero -
Automate e2e test with selenium of Django app in gitlab cicd -Error: selenium.common.exceptions.WebDriverException: neterror?e=dnsNotFound
This is the output of my cicd pipline which is failing base/tests/e2e_tests/test_register.py F [100%] =================================== FAILURES =================================== _____________ TestRegistrationPage.test_register_valid_credentials _____________ self = <test_register.TestRegistrationPage testMethod=test_register_valid_credentials> def test_register_valid_credentials(self): """ Test whether the registration process works flawlessly. This method asserts that after sucessful redirect url equals home. """ > self.driver.get("http://secprog:8080/") FAILED base/tests/e2e_tests/test_register.py::TestRegistrationPage::test_register_valid_credentials - selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=dnsNotFound&u=http%3A//secprog%3A8080/&c=UTF-8&d=We%20can%E2%80%99t%20connect%20to%20the%20server%20at%20secprog. Stacktrace: RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8 WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:193:5 UnknownError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:832:5 checkReadyState@chrome://remote/content/marionette/navigate.sys.mjs:58:24 onNavigation@chrome://remote/content/marionette/navigate.sys.mjs:330:39 emit@resource://gre/modules/EventEmitter.sys.mjs:148:20 receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.sys.mjs:33:25 This is my Dockerfile: # Stage 1: Build stage FROM python:3.12.0b2-alpine3.17 RUN apk update WORKDIR /app COPY . . EXPOSE 8080 CMD ["python", "manage.py", "runserver", "0.0.0:8080"] This is my .gitlab-ci.yml. in my build stage everything works fine and it gets passed. The problem is in my run_e2e_test. I don't know where my error is. I assume that there is a problem with how i define the alias for the services, but i don't know how the to services can communicate with each other: stages: - unit_tests - build - integration_tests - static_code_analysis - start_server - sec_vuln_assessment - e2e_tests run_build: stage: build image: docker:20.10.16 services: - docker:20.10.16-dind variables: DOCKER_TLS_CERTDIR: "/certs" before_script: # login working, but -p is unsecure. try --password-stdin - docker login registry.mygit.th-deg.de -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD script: - docker build -t registry.mygit.th-deg.de/pk27532/secprog . - docker … -
user.username shows incorrect information about the logged in user name
views.py def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) users/profile.html <h1>{{ user.username }}</h1> <h2>{{ user.email }}</h2> <img src="{{ user.profile.image.url }}" width="200" style="border: 3px solid black;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form }} {{ p_form }} <button type="submit">Update profile</button> </form> When I submit form with username that already exists, it shows error "A user with that username already exists", but user.username field is equal to that invalid existing username, but in database nothing changes. Also if this field doesn't pass any validators then it also shows this invalid data. I expected {{user.username }} to remain the same as in the database and as the logged in user's data -
How to import and use Django models inside new process outside views.py
I have some models inside 'models.py' inside 'app1' : ... class ChitaMoney(models.Model): chita_market = models.CharField( verbose_name=_('chita market name'), max_length=20 ) ... my 'views.py' calls a function from 'multy.py' from 'core' directory inside 'app1' 'multy.py' startes a new infinite process . when the process whants to import the models: from ..models import ChitaMoney this happens: Process chita_main: Traceback (most recent call last): File "C:\Users\David\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 314, in _bootstrap self.run() File "C:\Users\David\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 108, in run self._target(*self._args, **self._kwargs) File "D:\Django\JaNext_Boos_1\app1\core\multy.py", line 160, in chita_main_thread ins_l_t, ins_l_a = chita_init(chita_dtt) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Django\JaNext_Boos_1\app1\core\multy.py", line 112, in chita_init from ..models import ChitaMoney File "D:\Django\JaNext_Boos_1\app1\models.py", line 5, in class ChitaStock(models.Model): File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\db\models\base.py", line 129, in new app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Django==5.0.4 any help would be appreciated I had same problem without process importing models in top of .py files and after I import the models inside functions, I could use the models. But inside new process ... -
I'm getting a 503 error when I upload an image to a pre-trained model and try to get output using python + Django on a shared web host
Background: *Beginner here. * I made a simple app with some basic models and trained it to distinguish happy and sad faces. I made this and ran it in a local development server with Django which worked perfectly and I was even able to display the image after getting a non-logged-in user to upload. Then, I tried uploading the app to a non-local server. This server is part of a shared web hosting package and has cPanel. The app works fine till I upload the image and then it shows a 503 error. The server resource logs show that usage spikes when I upload the image and it is fed into the pre-trained neural network but nothing that would overpower the limits, only 75% of server physical memory being used. Server Specs: Server Specs TLDR: Uploaded a Django app with an Image Classification model which shows a 503 error after uploading the image from the front-end. Error Logs: 2024-05-05 16:03:28.355186: I external/local_tsl/tsl/cuda/cudart_stub.cc:32] Could not find cuda drivers on your machine, GPU will not be used. 2024-05-05 16:03:28.359620: I external/local_tsl/tsl/cuda/cudart_stub.cc:32] Could not find cuda drivers on your machine, GPU will not be used. 2024-05-05 16:03:28.396387: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is …