Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Have you ever see this problem on Django : frozen importlib._bootstrap
(env) PS C:\Users\wolf\Desktop\DashBoardv2\DashBoardv2> python manage.py migrate Traceback (most recent call last): File "C:\Users\wolf\Desktop\DashBoardv2\DashBoardv2\manage.py", line 22, in <module> main() File "C:\Users\wolf\Desktop\DashBoardv2\DashBoardv2\manage.py", line 18, in main self.models_module = import_module(models_module_name) self.models_module = import_module(models_module_name) File "C:\Users\wolf\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 879, in exec_module File "<frozen importlib._bootstrap_external>", line 1017, in get_code File "<frozen importlib._bootstrap_external>", line 947, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Hello, I created a project in django. And after having created my connection with my database and a router.py because I use a router page as I have databases. I don't use bootstrap in my project that's why I'm surprised to have this error that I don't understand and that I haven't been able to pass for several hours already! Je suis française si vous voulez répondre en français c'est avec plaisir ! Sinon je prends l'anglais aussi ! -
How to connect Django app hosted on heroku with redis (Heroku addon)
`config worker error 1)i have a celery worker and a beat which needs Redis as a broker , in my local environment i am able to connect to redis local host using and i am able to recieve the beat results as i needed 2)now when i wanted the redis to be the heroku addon so i followed this article https://devcenter.heroku.com/articles/connecting-heroku-redis#connecting-in-python and placed this code the config code as can be seen in the image in my settings.py file and started my worker as can be seen in worker image, after which is the output which i am getting can be seen in the error image` -
NoReverseMatch at /login.html/
this is the html form. I added action="{% url 'create_user_view' %}" to the html but the error says it is not a valid view. {% extends 'base.html' %} 2 3 {% block content %} 4 5 6 <div class="formbox"> 7 <form method="post" action="{% url 'create_user_view' %}"> 8 <h1 class="max"> Sign up </h1> 9 <input type ="text" class="max" id="fname" placeholder="username" name="username"> 10 <br> 11 <input type="email" class="max" id="email" placeholder="email" name="email"> 12 <br> 13 <input type="password" class="max" id="password" placeholder="password" name="password"> 14 <br> 15 <input type="submit" name="submit" class="max" placeholder="SUBMIT" id="submitid" formaction="logbook.html"> 16 <br> 17 <a href="home.html" id="links">already have an account?</a> Given below is the views.py file. I have created a view called create_user_view in the views.py file. However, the html form action does not find a valid view called create_user_view. from django.shortcuts import render from django.contrib.auth.models import User from django.shortcuts import render, redirect # Create your views here. def home_screen_view(request): print(request.headers) return render(request, "personal/home.html",{}) def login_view(request): print(request.headers) return render(request,"personal/login.html",{}) def create_user_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user = User.objects.create_user(username=username, password=password, email=email) # You can add additional fields to the User model as needed # Redirect to a success page return redirect('success') # If the request … -
Django migrations: when deploying on AWS ECS cluster
I have a djanog application. I have created an Docker image and pushed to ECR My docker image, has an entryscript which runs the python manage.py migrate I am planning to have a 4 tasks/containers of DJango running simultaneously So when each container is getting started, it will run the entrypoint script. Assume two containers are starting in parallel, each will try to run the entrypoint script. i.e the migrate So I am thinking this will collide with the database tables creation properly How to solve this issue -
Upload image to MongoDB from django rest api
I'm trying to set an api endpoint who get an image and send it to my mongodb database. I'm using djangorest api to create the endpoint. I tried to set my class image in my model like : from django.db import models from utils import database class Image(models.Model) : name = models.CharField(max_length=255) description = models.TextField(blank=True) image = models.ImageField(upload_to=database.post_image) but as you can expect upload_to=database.post_image doesn't work at all, because upload_to expect str, bytes or os.PathLike object, not NoneType. Do you have any idea? thanks you -
Run a django-admin command for a set duration inside of a test
Problem The test runs a django-admin command in a thread with a timeout. The test passes, but it hangs and I must manually stop its execution. I'm not familiar with threading, but I think the thread keeps running, which causes the test to "hang" after it passes. I'm looking for a solution that runs the command since this is more of an integration test and not a unit test with mocks. Any solution that runs the command for a set duration should work as long as there's proper test teardown and it doesn't cause issues for other tests during CI. Background Django-pgpubsub listens for PostgresSQL triggers by running python manage.py listen. I'm using this as a lightweight alternative to Django signals and celery for sending emails when a Shipment model instance's status field changes to specific values. The Test # transaction=True is needed listen command to work for django-pgpubsub @pytest.mark.django_db(transaction=True) def test_shipment_status_notifications_with_listen_command(testuser): user = testuser notification_settings = NotificationSettings.objects.get(user=user) notification_settings.failed_attempt = True notification_settings.save() cust_email = "test@somedomain.com" customer = Customer.objects.create(email=cust_email) order = Order.objects.create(customer=customer) def run_listen_command(): call_command("listen") listen_thread = threading.Thread(target=run_listen_command, daemon=True) listen_thread.start() # Change Shipment status to trigger the notification shipment = Shipment.objects.create(user=user, order=order) shipment.status = Shipment.FAILED_ATTEMPT shipment.save() sleep(1) # required to allow … -
Where do i paste my app password in django app?
Im trying to send email through my form in django application so i generated app password: somethingsomethi (for example) where do i paste it in my code? EMAIL_HOST_USER = 'something@gmail.com' EMAIL_HOST_PASSWORD = 'Something' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
Get Count of entries in all tables in database using django
Without mentioning the tables can i get count of entries in each table using django ORM. Don't want to use count() against each table manually. -
Why staticfiles aren't found when DEBUG=False (in production)?
This is django app and I am using DigitalOcean App platform for deploying my app. When I set DJANGO_DEBUG=True (in the enviroment veriables on DigitalOcean) all the static files are found by the server and my app works fine. BUT when I set DJANGO_DEBUG=False, then everything goes wrong: I get 500 error code When I checkout the "Runtime logs" there is the same error message: **ValueError: Missing staticfiles manifest entry for 'images/favicons/favicon.ico'** [gumroad-clone] [2023-04-04 09:20:11] [gumroad-clone] [2023-04-04 09:20:11] During handling of the above exception, another exception occurred: [gumroad-clone] [2023-04-04 09:20:11] [gumroad-clone] [2023-04-04 09:20:11] Traceback (most recent call last): [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner [gumroad-clone] [2023-04-04 09:20:11] response = get_response(request) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/utils/deprecation.py", line 134, in __call__ [gumroad-clone] [2023-04-04 09:20:11] response = response or self.get_response(request) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 58, in inner [gumroad-clone] [2023-04-04 09:20:11] response = response_for_exception(request, exc) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception [gumroad-clone] [2023-04-04 09:20:11] response = handle_uncaught_exception( [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 185, in handle_uncaught_exception [gumroad-clone] [2023-04-04 09:20:11] return callback(request) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapped_view [gumroad-clone] [2023-04-04 09:20:11] response = view_func(request, *args, **kwargs) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/views/defaults.py", line 102, in … -
How can the Django ORM perform an aggregate subquery in a WHERE statement?
I'm trying to construct the following query similar to this the Django ORM: SELECT * FROM table WHERE depth = (SELECT MIN(depth) FROM table) How can this be written in Django ORM notations? So far it seems hard to use an aggregate like this, because QuerySet.aggregate() isn't lazy evaluated, but executes directly. I'm aware that this basic example could be written as Model.objects.filter(depth=Model.objects.aggregate(m=Min('depth'))['m']) but then it does not evaluate lazily, and needs 2 separate queries. For my more complex case, I definitely need a lazily evaluated queryset. Any attempt to use .order_by().values().annotate(m=Min('depth').values('m') will result in a GROUP BY id that seems hard to loose. Also using Model.objects.annotate(m=Min('depth')).filter(depth=F('m')) will give a GROUP BY id, and include the m value in the main results as that's what annotate does. So far I've worked around this case by using QuerySet.extra(where=[...]) but I'd much rather like to see the ORM generate that code. -
Memory grows when using allow_join_result
I have two celery apps in my environment that are : app1 = Celery('app1', broker=BROKER_URL1, backend=BROKER_URL1) app2 = Celery('app2', broker=BROKER_URL2, backend=BROKER_URL2) From a django app within a web container I call a task in app1. That task needs to call a task within app2 and wait for its result. @app1.task() def task_app1(some_list): results = [] for i in some_list: with allow_join_result: task = app2.send_task('task_app2',kwargs={"id": i}) result = task.get() # This returns a relatively large JSON results.append(Result(r1=result["r1"], r2=result["r2"])) # Result is a Django model Result.objects.bulk_create(results) I noticed celery won't release memory after fetching result and instead it will grow infinitely. When i subtitute the result variable with a static JSON (or just read the JSON from a file), i don't experience that issue - that proves to me that the issue is not with the results list. How can i ensure Django "forgets" each indivdual call to app2? I tried del result, del task and gc.collect() too. -
Unable to open secure websocket connections in Django Rest Framework
Following is my asgi, which worked perfectly fine for normal websocket connection ws:// But it fails when the frontend tries to open secure websocket connection via wss:// Kindly let me know what needs to be done. application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) -
Use Column Value as key and another Column Value as dict from django ORM
In Django, I am trying an output without using a for loop to optimise the operation. My model structure seems like this class Test(BaseClass): id = model.UUIDField(uniq=True) ref = models.ForeignKey(Ref) name = model.CharField(max_length=50) Sample data in the table +--------------------------------------+--------+----------------+ | id | ref_id | name | +--------------------------------------+--------+----------------+ | 412dacb1-6451-4a1a-b3ac-09a30979b733 | 1 | test | | fa7abc8e-2070-40b6-af84-6a8d78676b89 | 2 | new_rule | | dd70a968-778c-4e45-9044-599effd243a6 | 3 | new_rule_test | +--------------------------------------+--------+----------------+ And I need to output in dict something like this { 1: { "name": "test", "id": UUID(412dacb1-6451-4a1a-b3ac-09a30979b733) }, 2: { "name": "new_rule", "id": UUID(fa7abc8e-2070-40b6-af84-6a8d78676b89) }, 3: { "name": "new_rule_test", "id": UUID(dd70a968-778c-4e45-9044-599effd243a6) } } In the above output, the key is ref_id and the value is again a dict having name and id. I have tried with annotate but it is not working. Only the below code which is working but I need more optimised as the data is very massive. res_dict = Test.objects.filter(publisher_state='Published').values('ref_id', 'name', 'id') final_dict = {row['ref_id']: {'name': row['name'], 'id':row['id']} for row in res_dict} -
I ran makemigrations and migrate but my columns are not reflecting in postgressql database
I'm new to Django, my version is 4.1. I had issues changing the field type of the id column in PostgresSql pgadmin4. But I overrode the ID by making migrations with id in midel.uuidfield like so: from django.db import models from django.contrib.auth.models import AbstractBaseUser import uuid class Profile(AbstractBaseUser): # id = None id = models.UUIDField(unique=True, editable=False, primary_key=True, verbose_name='ID') password = None This worked at last when I ran makegrations and changed the id from None to models.uuidfield before migrating. Now this column and every other column added is not reflecting in the database, that is the PgAdmin4. I tried to troubleshoot by adding a new column, created_time, like so: from django.db import models from django.contrib.auth.models import AbstractBaseUser import uuid class Profile(AbstractBaseUser): # id = None id = models.UUIDField(unique=True, editable=False, primary_key=True, verbose_name='ID') password = None created_time = models.DateTimeField(auto_now_add=True) Now after running makemigrations and migrate, the only record that got added to the database was the created_time. So i checked the migrations folder and in my 0001_initial.py file, it looks like this: # Generated by Django 4.1.7 on 2023-04-04 07:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('last_login', models.DateTimeField(blank=True, … -
stream multi videos using flask_socketio from Multi Clients to one server
can any one plz help me, to write a simple code in python based on Flask and flask_socketio, to recieve and process videos from multi clients in the same time. i used Threads but it's so difficult to apply it on flask_socketio. this is my old code based on socket library but i want to change it to flask_socketio: # Welcome to PyShine # In this video server is receiving video from clients. # Lets import the libraries import socket, cv2, pickle, struct import imutils import threading import pyshine as ps # pip install pyshine import cv2 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print('HOST IP:',host_ip) port = 9999 socket_address = (host_ip,port) server_socket.bind(socket_address) server_socket.listen() print("Listening at",socket_address) def show_client(addr,client_socket): try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: # if a client socket exists data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) # 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) text = f"CLIENT: {addr}" frame = ps.putBText(frame,text,10,10,vspace=10,hspace=1,font_scale=0.7, background_RGB=(255,0,0),text_RGB=(255,250,250)) cv2.imshow(f"FROM {addr}",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break client_socket.close() … -
How to generate jasper report in django using pyreportjasper library with mongodb native connection only?
Previously, I was using pyreportjasper==1.0.2 to generate jasper reports in my django application with mysql database. Now, I using the mongodb for data storage. I want to know how to configure jasper with mongodb native database connection to generate a jasper report. from pyreportjasper import JasperPy import pymongo mongo = pymongo.MongoClient('mongodb+srv://<user>:<password>@<cluster>/?retryWrites=true&w=majority') db = mongo['students']` `jasper = JasperPy() db_connection = { 'driver': 'none', 'database': 'students', 'collection': 'students', 'username': <user>, 'password': <password>, 'host': <cluster>, 'port': <port> } jasper.process( input_file, output_file = output, format_list=format_list, parameters=params, db_connection=db_connection )` I'm getting the following error Caused by: net.sf.jasperreports.engine.JRRuntimeException: No query executer factory registered for the "MongoDbQuery" language. -
Designing a relational data model for a cupboard of infinite depth
I'm trying to implement a relational data model for a cupboard with infinite depth. This means that: The cupboard can have a number shelves Each shelf can have a number of e.g. boxes Each box can have a number of e.g. drawers Etc. The name of each level of depth ('shelf', 'box', ...) can be customized, and the depth of the cupboard is theoretically infinite. I need to store items in the cupboard (e.g. I want to store socks in one of the drawers). Some items take up more space; one item can for instance be stored in a box, occupying all its drawers. Currently, my data model looks like this: Cupboard, with as one of its properties its configuration as a nested dict. For the example above, that's {'name': 'shelf', 'amount': 5, 'child': {'name': 'box', 'amount': 4, 'child': {'name': 'drawer','amount': 3, 'child': None} } } CupboardSpace which has the following properties: a foreign key to the Cupboard location, stored as JSON (eg {'shelf': 1, 'drawer': 2, 'box': 3}) When a new Cupboard is created, my application creates its CupboardSpaces. Item with (amongst others) a foreign key to the cupboard space(s) it occupies. What I want to be able to … -
How can I have object.model_set two foreign keys to the same model in Django?
Here is my code from django.db.models import Models class ChatRoom(Models.model): room_member_1 = models.ForeignKey( User, null=True, related_name="member_1", on_delete=models.SET_NULL ) room_member_2 = models.ForeignKey( User, null=True, related_name="member_2", on_delete=models.SET_NULL ) According to feature the User object could be room_member_1 and room_member_2. If one of the user object's has 5 ChatRoom then we can get user's chat rooms using following query like user_object.member_1 or user_object.member_2 Now i want to get user_object all chat room using one query without ChatRoom.objects.filter(Q(room_member_1=user_object)|Q(room_member_2=user_object)) query. Is it possible ? -
How can I configure redirectregex in compose file for traefic in a django project?
I used Cookiecutter to create a django project and now I want to configure traefik to redirect a specific url to another url with the same domain but a different path. This is my compose file: version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: &django build: context: . dockerfile: ./compose/production/django/Dockerfile image: telegrambots_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: telegrambots_production_postgres volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: telegrambots_production_traefik depends_on: - django volumes: - production_traefik:/etc/traefik/acme ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" - "0.0.0.0:5555:5555" labels: - "traefik.http.routers.redirect-router.middlewares=redirect-regex" - "traefik.http.middlewares.redirect-regex.redirectregex.regex=^mydomain\\.org\\/(.*)" - "traefik.http.middlewares.redirect-regex.redirectregex.replacement=mydomain.org/x/y/$${1}" - "traefik.http.middlewares.redirect-regex.redirectregex.permanent=false" redis: image: redis:6 celeryworker: <<: *django image: telegrambots_production_celeryworker command: /start-celeryworker celerybeat: <<: *django image: telegrambots_production_celerybeat command: /start-celerybeat flower: <<: *django image: telegrambots_production_flower command: /start-flower awscli: build: context: . dockerfile: ./compose/production/aws/Dockerfile env_file: - ./.envs/.production/.django volumes: - production_postgres_data_backups:/backups:z You can see in my compose file that I've put 4 lines under labels under traefik but this doesn't work. What should I do to fix this? -
django redirect url concatenating to the previous url, help me to stop concatenating
this is my previouse url - http://127.0.0.1:8000/viewbook/8/viewchapter/57/ this is the url I want to redirect - http://127.0.0.1:8000/viewbook/8/viewchapter/57/ but its redirect me to this url - http://127.0.0.1:8000/viewbook/8/viewchapter/57/ project - urls.py from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] home.urls.py from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('',views.home,name='home'), path('viewbook/<int:id>/', views.viewbook , name='viewbook'), path('viewchapter/<int:id>/', views.viewchapter , name='viewchapter'), path('viewpost/<int:id>/', views.viewpost , name='viewpost'), ] views.py def viewbook(response , id): book = Book.objects.get(id = id) allchapters = Chapter.objects.all() chapters = [] for chapt in allchapters: if chapt.Book.id == book.id: chapters.append(chapt) inputform = ChapterForm() if response.method == 'POST': form = ChapterForm(response.POST) if form.is_valid(): chapt = Chapter(Book = book , chapterNum = response.POST['chapterNum'] , chapterText = "") print(chapt) chapt.save() print(Chapter.objects.get(id= chapt.id)) return redirect('viewchapter/%i/' %chapt.id) inputform.fields["chapterNum"].initial =len(chapters) + 1 context = { 'book' : book, 'form' : inputform, 'chapters' : chapters } return render(response , 'viewbook.html' , context) def viewchapter(response , id): chapter = Chapter.objects.get(id = id) context = {'chapter' : chapter} return render(response , 'viewchapter.html', context) I think the problem is with this line return redirect('viewchapter/%i/' %chapt.id) I change it to return HttpResponseRedirect('viewchapter/%i/' %chapt.id) but bith of them are giving me … -
CSRF verification failed. Request aborted while deploying Django app on production
I am trying to setup my project on production but I am getting this error- Origin checking failed - https://mydomain does not match any trusted origins.I tried many solutions but none of them worked.I have deployed other django projects in past but this is first time I am getting this error. my django version is 3.12.4 This is what my django settings file looks like - """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) from .globalvariable import DATABASE # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['ip', 'domain', 'domain'] CORS_ORIGIN_WHITELIST = [ "domain", # Add any other allowed origins here ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'api', 'adminApi', 'rest_framework_api_key', 'room' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dashboardBackend.urls' CORS_ORIGIN_ALLOW_ALL = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Celery + Django - ModuleNotFoundError: No module named 'celery.backends.amqp'
I have no clue why I am getting this error. My ´requirements.txt´ file includes: amqp==5.1.1 celery==5.2.7 I have followed the standard configurations here: Any ideas what could be wrong? -
Django Crontab keeps add "No module named 'django.utils.importlib'"
Every time I try to run python manage.py crontab add or run my testing script I get this: python manage.py crontab add Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 257, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/opt/alt/python38/lib64/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django_crontab/management/commands/crontab.py", line 4, in <module> from django_crontab.crontab import Crontab File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django_crontab/crontab.py", line 13, in <module> from django.utils.importlib import import_module ModuleNotFoundError: No module named 'django.utils.importlib' Settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nema_app', 'user_auth', 'rest_framework', 'rest_framework.authtoken', 'django_crontab', ] . . . . . CRONJOBS = [ ('*/2 * * * *', 'nema_app.job.my_function') ] job.py: from user_auth.models import UserIntervalInfo def my_function(): # Your code here interval = UserIntervalInfo.objects.all()[0] interval.interval … -
Some files get "Static file referenced by handler not found"
I'm deploying to google app engine with Python/Django. I store css files and images in automatically created Cloud Storage. I can read css files, but not images. I think that the path is not wrong because the css file can be read. I think that it is due to the specifications of App Engine, but I do not know the detailed cause. Please support me. Of course it works fine locally. It is a situation where an error occurs only in production. ▼Version Python 3.9.12 Django 4.1.1 ▼Log(Cloud Storage) Static file referenced by handler not found: staticfiles/img/example.png/ ▼app.yaml runtime: python39 instance_class: F1 env: standard service: default entrypoint: gunicorn -b :$PORT config.wsgi:application includes: - secrets/secret.yaml handlers: - url: /static static_dir: staticfiles/ - url: /.* secure: always script: auto ▼folder -
Are channels and scrapy incompatible in Django?
This is the weirdest thing that happened to me There are scrapy and channels in my Django. After I installed channels3.0.5, my chat room can run normally, but my scrapy can't run normally, and scrapy stays at 2023-04-04 10:10:42 [scrapy.core .engine] DEBUG: Crawled (200) <POST http://pfsc.agri.cn/api/priceQuotationController/pageList?key=&order=> (referer: None), I debugged and found that I could not enter parse, I used wireshare to grab Get the data packet, there is a return value. I upgraded the channels to 4.0.0, and then my chat room can't link to the ws server, but scrapy can run normally thank you for your time scrapy log: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2023-04-04 10:10:42 [scrapy.middleware] INFO: Enabled item pipelines: ['spider.pipelines.SpiderPipeline_PFSC'] 2023-04-04 10:10:42 [scrapy.core.engine] INFO: Spider opened 2023-04-04 10:10:42 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2023-04-04 10:10:42 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2023-04-04 10:10:42 [scrapy.core.engine] DEBUG: Crawled (200) <POST http://pfsc.agri.cn/api/priceQuotationController/pageList?key=&order=> (referer: None) 2023-04-04 10:11:42 [scrapy.extensions.logstats] INFO: Crawled 1 pages (at 1 pages/min), scraped 0 items (at 0 items/min) scrapy spider: def __init__(self, **kwargs): super().__init__(**kwargs) self.total_prices = 1 self.url = 'http://pfsc.agri.cn/api/priceQuotationController/pageList?key=&order=' self.date = datetime.today().strftime('%Y-%m-%d') print('today is ' + self.date) date_list = PFSC_Price.objects.filter(reportTime=self.date) self.date_list = list(date_list.values()) for data in …