Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do aggregate raw sql with julian date in sqlite (with django)
I'm using sqlite3 and django. I wish to calculate the average for all the number of days between last_played and now. (Last_played is just a datetime field). I have so far: avg_days_last_played_sql = """ AVG(julianday('now') - julianday(played_at)) """ # Annotate the average days last played average_days_last_played = Song.objects.aggregate( avg_days_last_played=RawSQL(avg_days_last_played_sql, []) )['avg_days_last_played'] But it gives the error: TypeError: avg_days_last_played is not an aggregate expression -
View.py request error: Failed to establish a new connection: [Errno 111] Connection refused
I setup docker for my 2 django project (frontend | backend) this is my yaml `version: "3.12" services: mysql: image: mysql:8.0 container_name: mysql_db restart: always environment: MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' MYSQL_DATABASE: gfmic_frontend_db_v1 ports: - "3306:3306" volumes: - mysql_data:/var/lib/mysql networks: - backend event_backend: build: ./GFMIC_Backend container_name: GFMIC_Backend depends_on: - mysql volumes: - ./GFMIC_Backend:/django ports: - "8001:8001" expose: - 8001 environment: - DJANGO_SETTINGS_MODULE=GFMIC_Backend.settings networks: - backend event_frontend: build: ./GFMIC_Frontend container_name: GFMIC_Frontend depends_on: - mysql ports: - "8000:8000" expose: - 8000 volumes: - ./GFMIC_Frontend:/django environment: - DJANGO_SETTINGS_MODULE=GFMIC_Frontend.settings networks: - backend volumes: mysql_data: networks: backend: driver: bridge ` I got the error "Error fetching events: HTTPConnectionPool(host='127.0.0.1', port=8001): Max retries exceeded with url: /Event_Management/api/EventsDetails/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f85a023b710>: Failed to establish a new connection: [Errno 111] Connection refused'))" when I try to api request to my views.py example: `def events_list(request): title= "Events List" api_url = 'http://127.0.0.1:8001/Event_Management/api/EventsDetails/' # Replace with your API endpoint try: response = requests.get(api_url) response.raise_for_status() # Raises an HTTPError for bad responses (4xx and 5xx) events = response.json() # Parse the JSON response except requests.exceptions.RequestException as e: # Handle request exceptions (e.g., network errors) events = [] # Optionally log the error or provide feedback to the user print(f"Error fetching events: {e}") return … -
Rename my Django auth app to fix the "Application labels aren't unique" error
When I created my Django project I created an app called auth. I never used django.contrib.auth, instead I rolled my own authentication code. A User model without a password field, custom API views and serializes, login goes via magic links sent to email, etc. I didn't use the Django Admin so I never needed Django's auth implementation. Now I do want to add the Django Admin to my project, and for that I need to add django.contrib.auth and now I am running into some big problems because of the error django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth. Renaming my own auth app doesn't seem possible. I tried to change the label in its AppConfig but existing migrations are breaking in all sorts of fun and exiting ways. So I thought I'd import Django's auth app with a custom label, like so: # djangoauth.py from django.apps import AppConfig class DjangoAuthConfig(AppConfig): name = "django.contrib.auth" label = "django_auth" And then I added djangoauth.DjangoAuthConfig to INSTALLED_APPS. But that also doesn't work, as Django's auth app has migrations with the auth name being hardcoded, so changing the app label now breaks those migrations. I don't really know how to fix this problem. I really wish … -
Celery worker stops consuming tasks after some minutes for failed sync
On my django project I'm experiencing an issue with celery and redis as messages broker. Current versions: celery==5.3.6 redis==5.0.8 The problem can be described with this log: 2024-09-15 14:31:05 -------------- celery@5d4164b0472c v5.3.6 (emerald-rush) 2024-09-15 14:31:05 --- ***** ----- 2024-09-15 14:31:05 -- ******* ---- Linux-6.10.0-linuxkit-aarch64-with-glibc2.31 2024-09-15 12:31:05 2024-09-15 14:31:05 - *** --- * --- 2024-09-15 14:31:05 - ** ---------- [config] 2024-09-15 14:31:05 - ** ---------- .> app: core:0xffff8a65b550 2024-09-15 14:31:05 - ** ---------- .> transport: redis://:**@redis-12345.c123.eu-west-3-1.ec2.redns.redis-cloud.com:00000// 2024-09-15 14:31:05 - ** ---------- .> results: redis://:**@redis-12345.c123.eu-west-3-1.ec2.redns.redis-cloud.com:00000/ 2024-09-15 14:31:05 - *** --- * --- .> concurrency: 11 (solo) 2024-09-15 14:31:05 -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) 2024-09-15 14:31:05 --- ***** ----- 2024-09-15 14:31:05 -------------- [queues] 2024-09-15 14:31:05 .> celery exchange=celery(direct) key=celery 2024-09-15 14:31:05 .> celery:1 exchange=celery:1(direct) key=celery:1 2024-09-15 14:31:05 .> celery:2 exchange=celery:2(direct) key=celery:2 2024-09-15 14:31:05 .> celery:3 exchange=celery:3(direct) key=celery:3 2024-09-15 14:31:05 2024-09-15 14:31:05 [tasks] 2024-09-15 14:31:05 . apps.data_integration.tasks.celery_dataddo_process 2024-09-15 14:31:05 . apps.incrementality_experiment.tasks.geolift_market_match_task 2024-09-15 14:31:05 2024-09-15 14:31:05 [2024-09-15 12:31:05,926: INFO/MainProcess] Connected to redis://:**@redis-12345.c123.eu-west-3-1.ec2.redns.redis-cloud.com:00000// 2024-09-15 14:31:06 [2024-09-15 12:31:06,739: INFO/MainProcess] celery@5d4164b0472c ready. 2024-09-15 14:38:16 [2024-09-15 12:38:16,078: INFO/MainProcess] sync with celery@03ffef68e38c 2024-09-15 14:38:16 [2024-09-15 12:38:16,621: ERROR/MainProcess] Control command error: ValueError('not enough values to unpack (expected 3, got 1)') 2024-09-15 … -
Django error related to the pillow library
Yesterday everything worked fine, but today when I start it this error appears. Here's the error: Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in run_code File "E:\python-projects\dev_env\venv\scripts\pip.exe_main.py", line 4, in File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\cli\main.py", line 11, in from pip._internal.cli.autocompletion import autocomplete File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\cli\autocompletion.py", line 10, in from pip._internal.cli.main_parser import create_main_parser File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\cli\main_parser.py", line 9, in from pip._internal.build_env import get_runnable_pip File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\build_env.py", line 18, in from pip._internal.cli.spinners import open_spinner File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\cli\spinners.py", line 9, in from pip._internal.utils.logging import get_indentation File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\utils\logging.py", line 29, in from pip._internal.utils.misc import ensure_dir File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\utils\misc.py", line 43, in from pip._internal.utils.retry import retry File "E:\python-projects\dev_env\venv\Lib\site-packages\pip_internal\utils\retry.py", line 5, in from pip._vendor.typing_extensions import ParamSpec File "", line 1176, in _find_and_load File "", line 1147, in _find_and_load_unlocked File "", line 690, in _load_unlocked File "", line 936, in exec_module File "", line 1073, in get_code File "", line 1131, in get_data OSError: [Errno 22] Invalid argument Tell me how to solve this problem. When I try to install pillow, it gives the same error. Maybe I'm doing something wrong. -
Merging two wagtail page types into one
Let's say we end up with two page types ContentPage and Folder that do the same job and we want to consolidate them into one. Basically we want to merge Folder into ContentPage. I came up with next solution but want to be sure that I am not missing anything. migration: class Migration(migrations.Migration): dependencies = [ ... ] operations = [ # copy all `folder` specific fields into `contentpage` table migrations.RunSQL( """ INSERT INTO app_contentpage ( page_ptr_id, ..., body, ... ) SELECT ..., body, ... FROM app_folderpage; """ ), # update all tables that have references to `django_content_type` table # folder.content_type_id = 12 # contentpage.content_type_id = 11 migrations.RunSQL( """UPDATE wagtailcore_page SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailcore_modellogentry SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailcore_pagelogentry SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailcore_revision SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailcore_taskstate SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailcore_workflowstate SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailsearch_indexentry SET content_type_id = 11 WHERE content_type_id = 12;""" ), migrations.RunSQL( """UPDATE wagtailcore_workflowcontenttype SET content_type_id = 11 WHERE content_type_id … -
Mysql client on Django
Terminal image I tried installing mysqlclient for my django project. I have created the virtual env and also tried using brew command to install pkg-config. I am using mac but when locate to bash profile file it does not have any connection with mysql client. -
Handling Multiple User Inputs in Custom Django Form Field: Processing All Values
I am working on creating a custom form field in Django where users can input multiple text values dynamically at the frontend. However, I'm facing an issue where only the last text input value is being processed in the to_python method of the field, even though I can see all the input values in the Request.POST. Here is a simplified version of my code: #fields.py class MultiCharField(forms.Field): widget = Mywidget def __init__(self, *args, **kwargs): super(MultiCharField, self).__init__(*args, **kwargs) def to_python(self, value): print("value: " + str(value)) # it only prints the last text input if isinstance(value, list): print("list") else: print("here") if value is None: return [] return value if isinstance(value, list) else [value] <!-- mywidget.html --> <div class="choice"> <input type="text" class="form-control" id="id-{{ widget.name }}" name="{{ widget.name }}" {% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} /> <a href="#" class="add-field">Add Another</a> </div> <script> $( ".add-field" ).on( "click", function() { $('<div class="choice"><input type="text" name="{{ widget.name }}" /><a href="#" class="remove-field">Remove</a></div>').insertAfter($(this).parent()); $('.remove-field').on('click', function() { $(this).parent().remove(); }); }); </script> #forms.py class QuestionModelForm(forms.ModelForm): options = MultiCharField() class Meta: model = Question class Mywidget(forms.Widget): template_name = 'mywidget.html' def get_context(self, name, value, attrs=None): return {'widget': { 'name': name, 'value': value, }} def render(self, name, value, attrs=None, renderer=None): … -
Quill Rich Text Editor Not Submitting Content on First Click
I am using Quill's Rich Text Editor in my Django web application and I am facing an issue where the content from the editor is not being sent to the server upon the first form submission (first click of the submit button), but only sends after the second form submission (second click of the submit button). When I click on the submit button the first time, this is what I see on my django server when I print out the post request - POST Data: <QueryDict: {'csrfmiddlewaretoken': ['tokenHere'], 'content': ['']}> <ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Bad Request: /post-comment/ [14/Sep/2024 18:52:50] "POST /post-comment/ HTTP/1.1" 400 51 However, When I click on the submit button a second time, I see this - POST Data: <QueryDict: {'csrfmiddlewaretoken': ['TokenHere'], 'content': ['<p>testing form submit</p>']}> Sanitized content: <p>testing form submit</p> [14/Sep/2024 18:55:17] "POST /post-comment/ HTTP/1.1" 200 1438 Why Do i have to click it twice? This is the form in my detail.html - <!-- Leave a Comment --> <div class="mt-4"> <form id="comment-form" hx-post="{% url 'cloud:post_comment' %}" hx-swap="afterend" hx-target="#comment-list" hx-trigger="submit"> {% csrf_token %} <div class="mb-3"> <div class="quill-editor form-control" style="min-height: 150px;" placeholder="Ask a question or leave an answer..."></div> <input type="hidden" id="content" name="content"> </div> <button type="submit" class="btn subscribe-btn">Submit</button> … -
How to Access Checkout Session Metadata in Stripe Webhook for Payment Methods in Subscription Mode
I'm integrating Stripe Checkout in a Django application and handling webhooks to update user information based on payment events. However, I'm encountering issues accessing metadata associated with a Checkout Session when dealing with payment_method objects. Context: I have the following setup for Stripe Checkout: StripeCheckoutMonthlyView and StripeCheckoutYearlyView: Both create a Checkout Session with metadata (e.g., user_id, plan_type). Webhook Handler (stripe_webhook): Processes different event types from Stripe. Problem: In the payment_method.attached event, I need to access metadata that was included in the Checkout Session. However, the payment_method object does not include metadata and does not directly reference the Checkout Session. Here’s how my webhook handler looks: @csrf_exempt def stripe_webhook(request): payload = request.body event = None print('Stripe Webhook Received!') try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: # Invalid payload return HttpResponse(status=400) if event.type == 'payment_intent.succeeded': # Handle payment_intent.succeeded event pass elif event.type == 'payment_method.attached': payment_method = event.data.object # Issue: Payment method does not include metadata or session_id pass elif event.type == 'checkout.session.completed': session = event.data.object # Retrieve session metadata here pass else: print('Unhandled event type {}'.format(event.type)) return HttpResponse(status=200) What I Need: I need to update user information based on metadata that was included in the Checkout Session. Specifically: … -
How to get response content from a Response() object in a view decorator?
Let's say I have a decorator that can be applied to a DRF class based View. A basic version of the decorator i have is as follows:- `class LogRequest: def __init__(self, log_success=True, methods_to_log=None): self.log_success = log_success self.methods_to_log = methods_to_log if methods_to_log is not None else ["post"] def __call__(self, view_class): view_class.methods_to_log = self.methods_to_log view_class.log_success = self.log_success for method_name in self.methods_to_log: if hasattr(view_class, method_name): method = getattr(view_class, method_name) decorated_method = self.wrap_method(method) setattr(view_class, method_name, decorated_method) return view_class def wrap_method(self, method): @wraps(method) def wrapped_method(self, request, *args, **kwargs): method_name = request.method.lower() if method_name in getattr(self, "methods_to_log", []): log = Log(path=request.path, method=method_name) log.request_body = Log.parse_request_body(request) try: response = method(self, request, *args, **kwargs) except Exception as e: tb = traceback.format_exc() log.error_traceback = tb log.status_code = 500 log.response_body = str(e) log.save() return JsonResponse({"error": str(e)}, status=500) if self.log_success or response.status_code >= 400: log.status_code = response.status_code if 'application/json' in response.get('Content-Type', ''): response_content = response.rendered_content.decode("utf-8") log.response_body = response_content log.save() return response return method(self, request, *args, **kwargs) return wrapped_method` The problem is , when log_success is true and i want to log succesful responses or 400 errors, i am getting errors like JsonResponse' object has no attribute 'rendered_content' or 'Response' object has no attribute 'rendered_content' depending on what kind of response i … -
django authentication backend being ignored when specified
I have a two customer authentication backends: one for a standard login, and one for a two factor login. In my settings.py, I have them both listed AUTHENTICATION_BACKENDS = [ 'user_profile.auth_backends.TOTPBackend', 'user_profile.auth_backends.StandardLoginBackend', 'django.contrib.auth.backends.ModelBackend', ] I have them stored in the app folder (user_profile) in a file called auth_backends.py and the class names match: class TOTPBackend(ModelBackend): def authenticate(self, request, username=None, password=None, twofa_token=None, **kwargs): print("In TOTPBackend") # First, try to authenticate with the default method user = super().authenticate(request, username=username, password=password, **kwargs) if user is not None: ... And class StandardLoginBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("In StandardLoginBackend") # First, try to authenticate with the default method user = super().authenticate(request, username=username, password=password, **kwargs) if user is not None: ... Then I based on the view called from some logic, I want to explicitly call one or the other... class TwoFaLogin(APIView): permission_classes = (AllowAny,) def post(self, request): print("TwoFaLogin View") username = request.data['username'] passwd = request.data['password'] twofa_token = request.data['twofa_token'] user = authenticate(request, username=username, password=passwd, twofa_token=twofa_token, backend='user_profile.auth_backends.TOTPBackend') OR class StandardLogin(APIView): permission_classes = (AllowAny,) def post(self, request): print("StandardLogin View") username = request.data['username'] passwd = request.data['password'] user = authenticate(request, username=username, password=passwd, backend='user_profile.auth_backends.StandardLoginBackend') My challenge is that when making the authenticate call from the view, the backend parameter … -
Setting Manager for Django models dynamically
I'm trying to set my custom manager dynamically for given models. Here is a sample of my code class CustomManager(models.Manager): def active(self): return self.filter(name__startswith='c') def set_custom_manager(model_class, manager=CustomManager(), manager_name='objects'): setattr(model_class, manager_name, manager) return model_class class Facility(BaseModel): name = models.CharField(_("Name"), max_length=255) icon = models.ImageField(upload_to='location/facilities/') order = models.PositiveIntegerField(_("Order"), default=0) class Meta: verbose_name = _("Facility") verbose_name_plural = _("Facilities") ordering = ['order', 'id'] def __str__(self): return self.name set_custom_manager(Facility, CustomManager()) If I check manager class name of Facility instance, it's returning true >>> Facility.objects.__class__ <class 'apps.chargers.models.CustomManager'> But if I try to use default methods of models.Manager, it's returning error Facility.objects.all() Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.10/3.10.14/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 376, in __repr__ data = list(self[: REPR_OUTPUT_SIZE + 1]) File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 400, in __iter__ self._fetch_all() File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1928, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/njr/PycharmProjects/iwatt-backend/venv/lib/python3.10/site-packages/django/db/models/query.py", line 99, in __iter__ model_cls = klass_info["model"] TypeError: 'NoneType' object is not subscriptable -
API endpoing taking list as data in DRF
I have a class called Component in my models.py and I have an array of Component ids in React and I want to post them to my DRF API so I could get their data as my response. I want something like this: Request body: { compIds:[77,54,125], } Response: [ {id:77,name:"SMTH 77", price:120}, {id:54,name:"SMTH 54", price:140}, {id:125,name:"SMTH 77", price:61}, ] This is my Component model: class Component(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() def __str__(self): return self.name class Meta: verbose_name = 'قطعه' verbose_name_plural = 'قطعات' I don't know how I should write my Serializer and my viewset. -
Django Websocket Failing right after handshake if using PostgresSql
I developed the application using Django and I used Django channels in it for messages. My websocket connections were working fine as soon as I was using my local db.sqlite3 but when I shifted to using PostgreSQL hosted on AWS RDS, I start getting connection error: HTTP GET /community/groups/5/ 200 [5.13, 127.0.0.1:1905] WebSocket HANDSHAKING /ws/group/5/ [127.0.0.1:1908] HTTP GET /AI/tools-list/ 200 [2.72, 127.0.0.1:1905] WebSocket DISCONNECT /ws/group/5/ [127.0.0.1:1908] WebSocket HANDSHAKING /ws/notifications/ [127.0.0.1:1913] WebSocket DISCONNECT /ws/notifications/ [127.0.0.1:1913] Disconnected with close code: 1006 Note: Sometime, my notification websocket gets connected but group chat websocket never gets connected I tried connecting to websocket but it keeps on failing -
"Error 404: The resource is not found on this computer" when deploy Django Web Service to Render.com, deployment is successful, site is Live w/green
I have a Django web application that works great when testing it in local server. It uses generics.APIViews, and there is no index.html file and no static files to be served. I've read and abided by all the Render.com docs to deploy to Render.com including https://docs.render.com/deploy-django and https://docs.render.com/web-services#port-binding. I suspect it has something to do with port binding. Been researching different ways to make it work. I'm new to Django so probably something simple I'm missing: Below a shot of my settings.py: import os import dj_database_url from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = True DEBUG = 'RENDER' not in os.environ ALLOWED_HOSTS = ['*'] RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'API' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'jproj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Celery and Redis: Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'project' has no attribute 'celery'
Здраствуйте я пытаюсь подключить подключить асинхронные задачи через 'Celery' и брокер сообщений 'Redis'. Установил pip install celery создал файл celery.py рядом с settings.py и в нём прописал следующую конфигурацию import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.autodiscover_tasks(['accounts', 'shop']) Также, согласно рекомендациям из документации к Celery, добавил from .celery import app as celery_app all = ('celery_app',) Cоздал файл celery.py рядом с settings.py и в нём прописал следующую конфигурацию enter image description here import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.autodiscover_tasks(['accounts', 'shop']) Также, согласно рекомендациям из документации к Celery, добавил from .celery import app as celery_app all = ('celery_app',) C GitHab (https://github.com/microsoftarchive/redis/releases) скачал Redis-x64-3.0.504.zip распаковал и открыл файлы 'redis-server.exe' и 'redis-cli.exe' pip install redis и прописал в настройках проекта CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Далее в терминале: py manage.py runserver И ввёл: celery -A project worker -l INFO --pool=solo Но терминал выводит ошибку: Usage: celery [OPTIONS] COMMAND [ARGS] Try 'celery --help' for help. Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'project' has no attribute 'celery' Есть знатоки которые сталкивались с подобным и … -
RecycleBin() got unexpected keyword arguments: 'title', 'content_type', 'object_id', 'deleted_by'
I have a recycle bin model in my Django project that works fine with other models since I have overidden the delete function to soft delete any model object by using is_deleted=True in every model. class RecycleBin(models.Model): title = models.CharField( max_length=1000, verbose_name="Title", null=False, blank=False, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() deleted_object = GenericForeignKey("content_type", "object_id") deleted_by = models.ForeignKey( "Accounts.User", verbose_name="Deleted By", on_delete=models.CASCADE, blank=False, null=False, related_name="deleted_by", ) tenant = models.ForeignKey( "Tenants.Tenant", verbose_name="Tenant", max_length=1000, null=False, blank=False, on_delete=models.CASCADE, ) date_deleted = models.DateTimeField(verbose_name="Date Deleted", auto_now_add=True) due_deletion_date = models.DateTimeField(verbose_name="Due Deletion", default=None, null=True, editable=False) However, in my Files model, when i try to delete a file, i get an error RecycleBin() got unexpected keyword arguments: 'title', 'content_type', 'object_id', 'deleted_by'. class AllFilesManager(models.Manager): def get_queryset(self): return super().get_queryset() class ActiveFileModelManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class File(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=1000, null=False, blank=False) folder = models.ForeignKey( "Folders.Folder", on_delete=models.CASCADE, null=False, blank=False ) file = models.FileField( upload_to='tenants', storage=storage, max_length=1000, null=False, blank=False ) is_deleted = models.BooleanField(default=False, verbose_name="Is Deleted?") created_by = models.ForeignKey( "Accounts.User", verbose_name="Created By", on_delete=models.CASCADE, blank=False, null=False, related_name="file_created_by", ) modified_by = models.ForeignKey( "Accounts.User", verbose_name="Modified By", on_delete=models.CASCADE, blank=True, null=True, related_name="file_modified_by", ) tenant = models.ForeignKey( "Tenants.Tenant", verbose_name="Tenant", max_length=1000, on_delete=models.CASCADE, null=False, blank=False, ) date_created = models.DateTimeField(verbose_name="Date Created", auto_now_add=True) date_modified = models.DateTimeField(verbose_name="Date … -
Hosting React Frontend and Django Backend App in digital Ocean
Hi I'm trying to host React and django app in digital ocean apache server. When I do that successfully I get the Screen of Django rest framework as the page for the droplets IP address .I tried so many things but couldn't find a answer. Can someone tells me how to host django react app in digital ocean or namecheap shared hosting correctly Thanks In Advance. -
"PostgreSQL 12 or later is required (found 10.23)" Django error while connecting to PostgreSQL 16
Exception Type: NotSupportedError Exception Value: PostgreSQL 12 or later is required (found 10.23). The above exception is thrown by the db backend. The obvious assumption would a mismatch of versions; it isn't the case as I have made certain of this. The connection is to a remote db running on v16. Indeed, I have even migrated services but to no avail just to make sure. Also, it a bit imprecise as I was able to migrate, createsuperuser and create some objects from admins before the error was thrown again. settings/init.py: import os if os.environ.get("ENV_NAME") == 'production': from .production import * elif os.environ.get("ENV_NAME") == 'staging': from .staging import * else: from .base import * settings/base.py (contains base settings) import os from pathlib import Path import environ import dj_database_url env = environ.Env() # Take environment variables from .env file environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # add ".parent" after creating new folder for settings PROJECT_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-uoo(9irb!fcd5w-t7z*ua2go84_g4)b8q&8ofw*c)dabqoaf12' # SECURITY WARNING: don't run with debug turned on in production! … -
Use AlpineJS data in django-cotton component
I'm trying to use AlpineJS jointly with django-cotton components. I tried the following but it did not work. <div x-data="{ message: 'I ❤️ Alpine' }"> <c-card x-bind:title="message" x-text="message"></c-card> </div> with django-cotton card component simply copied from django-cotton Quickstart. <div> <h2>{{ title }}</h2> <p>{{ slot }}</p> </div> Is there a way to achieve this? -
Need suggestions on getting data from odoo inside Django on user navigation
I am developing a Complaint Management System with the admin side in Odoo and the subscriber side in Django. All complaints and subscriber information are managed on the admin/Odoo side, while the Django side is used solely for subscriber registration and recording of complaints. I need suggestions on what technology or methodology to use to retrieve subscriber information from Odoo when a subscriber logs in. There are various links where subscribers can click to view their information, which is retrieved from Odoo. These options are coming in my mind XML-RPC read ().The simplest option is to read specific form data from Odoo and display it in a Django form when users click on certain links. Django Channels Observable. I Appreciate clear guidance which technology stack I should use. -
Django session is not maintained on browser. login_required decorator is redirecting to login page
Background: I made a custom user model in django with Custom backend implementing authenticate and get_user methods. its all working fine with the requests and the user objects and stuff, but when i tried to use login_required for a view, it sends the page back to login page. the user is being authenticated and all the stuff is happening. but login is not being maintained on the browser Github Link: https://github.com/WarLoRDlArS/Prodvi Login View: view is located in Prodvi/users/views.py def login_page(request): if request.method == "POST": pid = request.POST.get("pid") password = request.POST.get("password") if not Users.objects.filter(pid=pid).exists(): messages.error(request, 'Invalid Username') return redirect('users:login') user = authenticate(request, pid=pid, password=password) if user is None: messages.error(request, 'Invalid Credentials') return redirect('users:login') print("User is None") login(request, user) print("Login Successful") # Login is a success return redirect('home:index') # Test Login # pid: 000000 # password: abc return render(request, 'users/login.html') Index page code: index is located in Prodvi/home/views.py @login_required(login_url='users:login') def index(request): print("came here") return HttpResponse('Welcome To Prodvi') i tried with various stuff like changing session timeout, setting session_cookie_secure, debugging using print statements. when i remove login_require, it works but otherwise it doesnt. -
I'm having troubles migrating my company's data from Magento to Django Rest Framework
I observed that the SQL tables were not organised enough for a typical migration, so I decided to work on a new lighter DB and utilise Django because of its stability to handle the seeding of the new DB from the Magento DB through the API it provides. The major tables I need for the new DB are: Products Categories Brands Customer Details I have a script that successfully seeds categories and brands. I am yet to attempt Customer Details, and the major issue is that the products have images attached to them, and I am not sure how to do the migrations of images effectively. Also the categories are forgetting their parent category, reason is since they are all creating at the same time, the parent category ID will always return not found. I created some scripts already, seed categories and seed brands fully functional. I created another sript to run all the necessary migrations too. #!/bin/bash set -e GREEN='\033[0;32m' RED='\033[0;31m' RESET='\033[0m' GAP="\n\n\n" echo "Installing requirements..." pip install -r requirements.txt echo -e "${GREEN}Requirements installed!${RESET}${GAP}" echo "Migrating database..." python manage.py makemigrations python manage.py makemigrations helpers api python manage.py migrate echo -e "${GREEN}Migration complete!${RESET}${GAP}" echo "Seeding Image..." python manage.py seed_image echo … -
Django queryset stops working after multiple uses and filters
I am currently working on a task which requires me to divide my model data into multiple parts based on conditions and then process them differently. I am able to get data from my model correctly and check all available details that they exists. But after applying certain number of filters, suddenly the queryset stops working and don't give the correct results. I don't know why this is happening, can someone explain? Here is part of my code that is causing issue: def test_selection(): po_numbers = ( Model1.objects .filter(schedule__isnull=True) .filter(order_hold_type__isnull=True) .filter(so_line_status='Awaiting Supply') .values_list("customer_po", flat=True) .distinct() ) rows = Model1.objects.filter(customer_po__in=po_numbers).annotate( total_qty=Sum(F('line_item_quantity')*F('cup_count')) ).all() old_sizes = Sizes.get_old_sizes() old_po = rows.filter( item_size__in=old_sizes).values_list('customer_po', flat=True).distinct() rows = rows.filter(~Q(customer_po__in=old_po)).all() partially_scheduled = rows.filter( customer_po__in=list(rows.filter(schedule__isnull=False).values_list( 'customer_po', flat=True).distinct()) ).all() unscheduled = rows.filter( ~Q(customer_po__in=list(partially_scheduled.values_list( 'customer_po', flat=True).distinct().all())) ).all() model2_po = Model2.objects.values_list('customer_po', flat=True).distinct() g1 = unscheduled.exclude(customer_po__in=model2_po) po_list = g1.values_list('customer_po', flat=True).distinct() print(rows.count(), po_list) I thought the problem is in my flow so I created a separate function to test this and this is the point after which the problem starts occurring. This is not throwing any error but coming up empty and I have tried searching for anyone having similar issue but cannot find anything. I have tried following things uptil now: Use filter(~Q()) …