Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i calculate the task estimation in agile project management ? and how can i do it in code or can what dataset i use for it?
me and my team work on a project EI scrum planner it's important features that it can detect your emotions and give your task about it and the the important feature that we estimate the task in AI that it will automatically learn from the past tasks that have been estimated from the previous 2 sprints so i want to ask about this point how can i do the estimation of task i know something like calculate it with Pert law but is there any dataset that could i use instead of make my dataset? it is my graduation project i know something like calculate it with Pert law -
Extra "[]" characters appearing before login fields for django admin
On my Django admin login page I see extra "[]" before the username and password fields: and I really cannot figure out where they are coming from. I'm using Django v5.1.3 and I haven't made any extra customisations to the django admin, so it should only be loading the default CSS and JS that the admin site natively comes with. It happens on both Brave and Firefox browsers. I'd really like to get rid of these, but have no idea where to start... let me know if any extra code/settings would be helpful to figure out. Any help much appreciated. -
Django session key not found using str(instance.id)
This is my scenario I have a signal on cart apps which is raised when admin delete a product in django but searching for the product key in the session is not working below is the code that I'm using from django.db.models.signals import post_delete from django.dispatch import receiver from store.models import Product from django.contrib.sessions.models import Session @receiver(post_delete, sender=Product) def update_cart_on_product_delete(sender, instance, **kwargs): # Get all sessions for session in Session.objects.all(): data = session.get_decoded() print(data) if str(instance.id) in data: print(f"Instance ID {instance.id} found in cart") print(instance.id) del data[str(instance.id)] session['cart'] = data session.save() else: print(f"Instance ID {instance.id} not found in cart") And on the terminal when I get the result it appear like this {'session_key': {'47': 1}} Instance ID 47 not found in cart as you can see clear the INSTANCE.ID is in the cart '47' but django code is not able to find it even that I'm converting the key to str. Pls someone help me on this. -
How to display Field Quill in Django Views?
For my forum I am trying to use Quill Rich Text editor to format my Posts and comments. class Topic(models.Model): title = models.CharField(max_length=70, blank=False, null=False) description = QuillField(default="") And managed to create some content <class 'django_quill.fields.FieldQuill'> This is how it looks on admin form I have tried display it in views using <div class="">{{topic.description.html| safe}}</div> This is how it looks in Views I am using django-quill package enter link description here I have included all the style and script tags as recommended and still the styles are not applying. Any ideas how I can display the content as is. I have tried: Converting the delta type {"ops":[{"attributes":{"bold":true},"insert":"dqwdqwdqdqdq"},{"insert":"\n"}]} into html before saving the model. failed with error TypeError: 'FieldQuill' object is not subscriptable Please recommend reliable packages to convert delta to html or display the content with all formatting. TIA -
How would you ignore a trigger within another trigger with django-pgtrigger
I am updating tbla."field_2" from a trigger in tblb. Except tbla."field_2" is protected with a pgtrigger.ReadOnly trigger. This works without the pgtrigger.ReadOnly trigger in TblA. How would I do it and keep the pgtrigger.ReadOnly trigger on TblA.field_2? Model TblA(models.Model): field_1 = models.CharField(max_length=20) field_2 = models.PositiveIntegerField(default=0) class Meta: triggers = [ pgtrigger.ReadOnly( name='read_only_field_2', fields=['field_2'] ) ] class TblB(models.Model): field_a = models.ForeignKey(TblA, on_delete=models.SET_NULL) class Meta: pgtrigger.Trigger( func=pgtrigger.Func(''' IF (NEW."{columns[field_a]}" IS NOT NULL) THEN UPDATE "tbla" SET "tbla"."field_2" = "tbla"."field_2" + 1 WHERE "tbla"."id" = NEW.{columns[field_a]} END IF; RETURN NEW; ''') ), when=pgtrigger.Before, operation=pgtrigger.Insert, name='increment_tbla_field_2' ), I was thinking to mimic pgtrigger.ignore() functionality within the trigger by using set_config however I am not very familiar how persistent set_config is. Do I need to clean up at the end of the trigger? Is this doable? set_config('pgtrigger.ignore', '{myapp:pgtrigger_read_only_field_2_c8215,pgtrigger_read_only_field_2_c8215}', true) -
update the status of a buy a product button when we have more than one of that product in page with JavaScript in a Django app
I am Tring to update a buy button base of the quantity of the colors on that product in my django app with javaScript my code is working if i have one from that item in my page but some where in code when i have some swiper to show favorite products must sell products or must see products i have same item in diffrent places and when i try to chnage the color of the products it change the first one of the kind of this prodcut in page i have this view to check the product color quantity : def quantity_of_product_with_color(request): color_id = request.GET.get('color') try: product_color = ProductColor.objects.get(id=color_id) data = { 'in_stock': product_color.quantity > 0, 'quantity': product_color.quantity } except ProductColor.DoesNotExist: data = { 'in_stock': False, 'quantity': 0 } return JsonResponse(data) and for exampel i have this html code : {% for item in discounted_products %} <div class="swiper-slide"> <div class="product-box"> <div class="product-timer"> <div class="timer-label"> <span>{{ item.discount }}% تخفیف</span> </div> <div class="timer"> <div class='countdown' data-date="{{ item.offer_end.date|date_convertor }}" data-time="{{ item.offer_end.time|time_convertor }}"> </div> </div> </div> <div class="product-image"> <img src="{{ item.images.all.0.image.url }}" loading="lazy" alt="{{ item.images.all.0.image_alt }}" class="img-fluid p-2"> </div> <div class="product-title"> <div class="title"> <p class="text-overflow-1">{{ item.name }}</p> <span class="text-muted text-overflow-1"></span> </div> <div class="rating"> … -
DRF auth via Azure AD
Which Python package do you recommend for implementing authentication via Azure AD in a Django Rest Framework (DRF) project? So far, I have tried two packages, but both had issues: django-azure-auth: This package didn't display the login endpoints, making authentication impossible. django_auth_adfs: I had issues with configuration. I kept getting errors regarding the CLAIM_MAPPING and USERNAME_CLAIM properties. -
How to share the data folder from website to google drive
1.I am clueless to approach the problem to share the folder data information via a to google drive with an expiry date and time.So If can one have worked on this API's can help me out it can be any programming language just need the work flow to reach the approach.As per my company organization we are working on python language with Django Framework(DRF) and help me out which library we can use for this. 2. sharing the data happening via link, which is the library to share and save drive folder using python and django , as a backend how to send this data in payload and facing an issue to share the folder information(data) through the api. 3. if the user want to share some folder or save that folder in his google drive than how to send the payload response. Nothing................................. -
Django Deployment Code Execution Error vs Local Correct Execution
in my local server ( windows ) my project works fine, when i send a month from the filter via post request to my backend view it does its processing however in deployment (linux based server ) that requests somehow turns into a get request and doesnt send anything. We use ajax to send the request via fetch(url) Any assistance would be greatly appreciated I tried changing the csrf and cors and header values being sent to the linux server in order to bypass the error but nothing happens. Gunicorn Configuration [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target --- [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/home/zeritek/cras ExecStart=/home/zeritek/cras/venv/bin/gunicorn \ --access-logfile /var/log/gunicorn-access.log --error-logfile /var/log/gunicorn-error.log \ --workers 3 \ --timeout 3000 \ --threads 3 \ --keep-alive 3000 \ --worker-class gevent \ --bind unix:/run/gunicorn.sock \ Extraction.wsgi:application [Install] WantedBy=multi-user.target Nginx Configuration server { listen 80; server_name 1440.25554.1555.4266; client_body_timeout 300; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/zeritek/cras; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; proxy_read_timeout 600; # Increase this value proxy_send_timeout 600; # Increase this value proxy_connect_timeout 600;# Increase this value } } -
Django Celery. Publush post on publish_date
I have a Post model. There is a field publish_date. If the post has a planned status, then i need to perform the publishing function on the publish_date. How can I do this? models.py: class Post(models.Model): STATES = ( ('draft', 'Draft'), ('published', 'Published'), ('planned', 'Planned') ) state = models.CharField(choices=STATES, default=STATES[0][0]) channels = models.ManyToManyField('channel.Channel') creator = models.ForeignKey('authentication.User', on_delete=models.SET_NULL, null=True) publish_date = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @receiver(post_save, sender=Post) def reschedule_publish_task(sender, instance, **kwargs): # There should be a task setting for a specific time here, as I understand it I tried to do this, but it didn't work, the task is not completed. models.py @receiver(post_save, sender=Post) def reschedule_publish_task(sender, instance, **kwargs): task_id = f"publish_post_{instance.id}" if instance.state == 'planned' and instance.publish_date: publish_post.apply_async((instance.id,), eta=instance.publish_date, task_id=task_id) tasks.py @shared_task def publish_post(post_id: int) -> None: from .models import Post post = Post.objects.filter(id=post_id).first() if post: if post.state == 'planned' and post.publish_date <= now(): post.state = 'published' post.save() -
TypeError: 'type' object is not subscriptable with prefetch_related
I’m trying to return a specific queryset using prefetch_related to optimize future queries, but I’m encountering an issue. When I don’t specify a return type, the code works fine. However, I want to understand the actual return type and what’s happening when I specify the return type as QuerySet[ABCInstance]. Here’s the code I’m working with: def _fetch_abc_instances(self) -> QuerySet[ABCInstance]: # Prefetch related "cde_instances" to avoid N+1 query issues return self.xyz_instance.abc_instances.prefetch_related("cde_instances") In this case: xyz_instance has a one-to-many relationship with abc_instances. abc_instances has a one-to-many relationship with cde_instances. My current environment: Python 3.6.7 Django 2.0.2 I’m expecting the return type to be ABCInstance, but since the query involves prefetching related data, the actual return type is different. I’d like to understand what the actual return type is in this case. -
Query for filter blogpages by category in wagtail graphiql
Help please if i have blog category relationship then how can i fetch blogs by category. Anyone know query for that. i am using wagtail grapple If i want to fetch blogs by category id or slug how can i do what is the graphiql query for that This is my models page = ParentalKey( "BlogPage", related_name="blog_category_relationship", on_delete=models.CASCADE ) category = models.ForeignKey( "base.Category", related_name="category_blog_relationship", on_delete=models.CASCADE ) panels = [FieldPanel("category")] @register_paginated_query_field("blogpage") class BlogPage(Page): introduction = models.TextField(help_text="Text to describe the page", blank=True) image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", help_text="Landscape mode only; horizontal width between 1000px and 3000px.", ) body = StreamField( BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True ) subtitle = models.CharField(blank=True, max_length=255) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) date_published = models.DateField("Date article published", blank=True, null=True) content_panels = Page.content_panels + [ MultipleChooserPanel( "blog_category_relationship", chooser_field_name="category", heading="Categories", label="Category", panels=None, min_num=1, ), FieldPanel("subtitle"), FieldPanel("introduction"), FieldPanel("image"), FieldPanel("body"), FieldPanel("date_published"), MultipleChooserPanel( "blog_person_relationship", chooser_field_name="person", heading="Authors", label="Author", panels=None, min_num=1, ), FieldPanel("tags"), ] graphql_fields = [ GraphQLCollection( GraphQLForeignKey, "categories", "base.Category" ), GraphQLString("subtitle"), GraphQLString("introduction"), GraphQLString("image_url"), GraphQLStreamfield("body"), GraphQLString("date_published"), GraphQLString("tags"), GraphQLCollection( GraphQLForeignKey, "authors", "base.Person" ), ] search_fields = Page.search_fields + [ index.SearchField("body"), ] -
Trying to connect my backend to my frontend
EditTransaction.js import React, { useEffect, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; export default function EditTransaction() { const params = useParams() const [initialData, setInitialData] = useState() const [validationErrors, setValidationErrors] = useState({}) const navigate = useNavigate() function getTransaction() { fetch("http://127.0.0.1:8000/transactions/" + params.id) .then(response => { if (response.ok) { return response.json() } throw new Error() }) .then(data => { setInitialData(data) }) .catch(error => { alert('Unable to read the Transaction details') }) } useEffect(getTransaction, [params.id]) async function handleSubmit(event) { event.preventDefault() const formData = new FormData(event.target) const Transaction = Object.fromEntries(formData.entries()) if (!Transaction.name) { alert("Please fill the Name field") return } try { const token = '852de93b4848505296fb5fe56e41a6d1501adfca'; const response = await fetch("http://127.0.0.1:8000/transactions/" + params.id, { method: 'PATCH', body: formData, headers: { 'Authorization': `Token ${token}` }, }); const data = await response.json() if(response.ok){ //Transaction Created Correctly! navigate('/admin/transaction') } else if (response.status === 400){ setValidationErrors(data) } else( alert('Unable to Update Transaction') ) } catch(error) { alert('Unable to connect to the server') } } return( <div className="container my-4"> <div className="row"> <div className='col-md-8 mx-auto rounded border p-4'> <h2 className= "text-center mb-5">Edit Transaction</h2> <div className="row mb-3"> <label className='col-sm-4 col-form-label'>ID</label> <div className= 'col-sm-8'> <input readOnly className='form-control-plaintext' defaultValue={params.id}/> </div> </div> { initialData && <form onSubmit={handleSubmit}> <div className="row … -
Images do not appear on a page even though they are already in a DB (Django)
I try to learn how to deploy my django project. I have a form in which user can upload his image. The image is a content for ImageField of a Recipe model. Uploading process is working as expected but when I try to display these pictures on the page they just dont appear. Here's my code: settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py (project one): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('user_auth.urls')), path('main/', include('main_app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: class Recipe(models.Model): author = models.ForeignKey(UserExtended, on_delete=models.CASCADE, related_name='recipies') title = models.CharField(max_length=150, null=False) category = models.ForeignKey(RecipeCategory, related_name='recipies', on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to="images/", null=False) short_description = models.CharField(max_length=250, null=False) tutorial = models.TextField(null=False, default='') uploaded_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(UserExtended, related_name='liked_recipies') likes_count = models.SmallIntegerField(default=0) def __str__(self): return f'{self.author} {self.title}' example of my template: <img class="full-recipe-image" src="{{ recipe.image.url }}" alt="Фото блюда"> Any help would be a blessing to me since I'm pretty desperate. I tried to alter my urls.py and was struggling with MEDIA_ROOT / MEDIA_URL problem -
404: NOT_FOUND error on Vercel - Django deployment
I deployed a Django project on Vercel and it shows the deployment is successful. However, when I try to open the website, it shows the error: 404: NOT_FOUND Code: NOT_FOUND ID: lhr1:lhr1::6n29s-1732227821846-0cc9eddbb440 My Django project can be found in the following link: https://github.com/RailgunGLM/railgunglm-com I tried solving the problem by, as some solutions on stackoverflow suggested, inserting a vercel.json file and a build.sh file, adding the line app = application at the very end of wsgi.py, including .vercel.app in my ALLOWED_HOSTS in setting.py, and lastly, installed whitenoise. However, none of them seems to work. The application works normally in my local machine, but I'm not sure whether I made a mistake in one of these files. I would be really appreciated if there is a solution to fix this problem. -
Changing the session key to a different user model field
I have my own user model. Django derives the session key from the primary key in this model. However, I wish to use a different field as the primary key / session key. The problem with changing the primary key is that it will break existing logged in sessions since the Django session middleware code tries to convert the session key to the type of the primary key defined in the model. I wish to change from username to a uuid. I thought I could work around this by having different auth backends since the session stores the backend but this type conversion occurs before Django calls the get_user method in my custom backends. Is there a way to uses a new field as the primary key? -
Constraint to forbid NaN in postgres numeric columns using Django ORM
Postgresql allows NaN values in numeric columns according to its documentation here. When defining Postgres tables using Django ORM, a DecimalField is translated to numeric column in Postgres. Even if you define the column as bellow: from django.db import models # You can insert NaN to this column without any issue numeric_field = models.DecimalField(max_digits=32, decimal_places=8, blank=False, null=False) Is there a way to use Python/Django syntax to forbid NaN values in this scenario? The Postgres native solution is to probably use some kind of constraint. But is that possible using Django syntax? -
DRF serializer missing fields after validation
I have a simple DRF serializer: class CustomerFeatureSerializer(serializers.Serializer): """ Serializer for a customer feature. """ feature_id = serializers.CharField() feature_value = serializers.SerializerMethodField() feature_type = serializers.CharField() name = serializers.CharField() def get_feature_value(self, obj): """ Return the feature_value of the feature. """ return obj.get("feature_value", None) the feature_value field is a method field since it can be either a boolean, an integer, or a string value (so for now I just kept it as a method field to fetch the value). I am using this to serialize some objects that I am hand-generating (they do not correspond 1:1 with a model) but for some reason after validation the name and feature_value fields are just completely disappearing. for feature in toggleable_features: display = { "feature_id": feature.internal_name, "name": feature.name, "feature_value": profile.feature_value(feature) if profile.has_feature(feature.internal_name, use_cache=False) else False, "feature_type": feature.type, } features.append(display) print(display) print(features) serializer = CustomerFeatureSerializer(data=features, many=True) print(serializer.initial_data) serializer.is_valid(raise_exception=True) print(serializer.validated_data) return Response(serializer.validated_data) and the print statements output: {'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'} [{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}] [{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}] [OrderedDict([('feature_id', 'feat-id'), ('feature_type', 'boolean'), ('name', 'feat name')])] the value is just gone. Any idea why this could be happening? Is the object I am … -
Django SSL Redirect causing local development connection issues in Chrome
After setting SECURE_SSL_REDIRECT=True in my settings.py but False in my environment variables for local development and restarting the server and browser I cannot connect to my website via local host and get the You're accessing the development server over HTTPS, but it only supports HTTP. [21/Nov/2024 11:28:50] code 400, message Bad request syntax ('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03èª\x19óÆð?ë-\x99âÆH\x13V\x08{zm') error. It works when I open it incognito and in other browsers but not in the current browser(Chrome). Here is my settings.py: SECRET_KEY = env.str("SECRET_KEY") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) SECURE_HSTS_SECONDS = env.int("DJANGO_SECURE_HSTS_SECONDS", default=2592000) SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) SESSION_COOKIE_SECURE = env.bool("DJANGO_SESSION_COOKIE_SECURE", default=True) CSRF_COOKIE_SECURE = env.bool("DJANGO_CSRF_COOKIE_SECURE", default=True) Environment variables: DEBUG=True SECRET_KEY=bTU5cQLjBGapg3d......mrVglq1CEhbk DJANGO_SECURE_SSL_REDIRECT=False DJANGO_SECURE_HSTS_SECONDS=0 DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False DJANGO_SECURE_HSTS_PRELOAD=False DJANGO_SESSION_COOKIE_SECURE=False DJANGO_CSRF_COOKIE_SECURE=False I've deleted cookies for both localhost and 127.0.0.1, restarter Chrome and still had the same error in the end. -
How to run django-ckeditor-5 with docker container
I have a django app and I installed the module django-ckeditor. I can run the app with the command: python manage.py runserver without any problems. But after I build the docker container with the command: docker-compose -f docker-compose-deploy.yml up I get this errors: import_module("%s.%s" % (app_config.name, module_to_search)) web-1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web-1 | return _bootstrap._gcd_import(name[level:], package, level) web-1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import web-1 | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load web-1 | File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked web-1 | File "<frozen importlib._bootstrap>", line 680, in _load_unlocked web-1 | File "<frozen importlib._bootstrap_external>", line 850, in exec_module web-1 | File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed web-1 | File "/usr/src/app/DierenWelzijnAdmin/admin.py", line 17, in <module> web-1 | from ckeditor.widgets import CKEditorWidget web-1 | ModuleNotFoundError: No module named 'ckeditor' web-1 | [2024-11-21 15:50:43 +0000] [7] [INFO] Worker exiting (pid: 7) web-1 | [2024-11-21 15:50:43 +0000] [1] [ERROR] Worker (pid:7) exited with code 3 web-1 | [2024-11-21 15:50:43 +0000] [1] [ERROR] Shutting down: Master web-1 | [2024-11-21 15:50:43 +0000] [1] [ERROR] Reason: Worker failed to boot. I added ckeditor in settings.py file: INSTALLED_APPS = [ 'django_ckeditor_5' I added ckeditor in requirements.txt file: django-ckeditor-5==0.2.15 I … -
Is there any way to get the windows user id in Django API
I am writing a Django API which will be hosted on IIS server and will be called from Angular Front end. I am trying to get the Windows User name who is calling my API. I am no finding any way for doing this. I tried multiple options like request.user, REMOTE_USER etc. None of them are working. They are giving Anonymous User always. Please help me with step by step process. I tried request.user object. This always gives AnonymousUser. I tried Remote_USER option as well but no luck. I am expecting to get user name of windows login. -
Django Test Environment Runs Twice and Fails When Using if not IS_PRODUCTION and INJECT_FAKE_DATA
Description: I'm encountering a strange issue in my Django test environment. When running my test suite, the environment appears to initialize twice, causing a specific test to pass the first time and fail on the second run. The problem seems to be related to the following conditional statement in my settings.py file: if not IS_PRODUCTION and INJECT_FAKE_DATA: # Code for injecting fake data Environment Details: Django version: 5.1.1 Python version: 3.12.1 Test Framework: pytest with pytest-django Database: MongoDB for test What Happens: When I run my tests, the environment is reloaded twice (as evidenced by logs). On the first initialization, everything works as expected, and the test passes. On the second run, the same test fails due to the environment not behaving as intended. INFO:C:\path\to\settings.py changed, reloading. INFO:INJECT_FAKE_DATA is True. INFO:Fake data mode activated. INFO:Watching for file changes with StatReloader ... Performing system checks... System check identified no issues (0 silenced). ... First run: test passes. Second run: test fails with inconsistent state. and PS C:\Users\Chevr\OneDrive\Bureau\eOnsight\eOnsightApi\eonsight-api> pytest app_auth ============================================================= test session starts ============================================================== platform win32 -- Python 3.12.1, pytest-8.3.3, pluggy-1.5.0 django: version: 5.1.1, settings: eOnsight_api.settings (from ini) rootdir: C:\Users\Chevr\OneDrive\Bureau\eOnsight\eOnsightApi\eonsight-api configfile: pytest.ini plugins: Faker-30.0.0, django-4.9.0, factoryboy-2.7.0, mongo-3.1.0 collected 2 items app_auth/tests/test_auth_viewset.py::test_login … -
Django devserver load once
I am trying to develop a django application it use paddelocr take sometime to initiate. so when ever I am trying to change something and test it I have to wait 5 sec for the paddleocr to initiate again. Is there a way to load the model only once when i start the dev server and not everytime I make some changes. I have tried adding the model initalization in the setting.py assuming that it will only run only that didn't work. I have also tried one of gpts suggestion of using thread but no luck so far -
ModuleNotFoundError: No module named 'pageflows.website'
I am making a project in Django, and trying to optimise my code and trying to implement Don't repeat techniques. Here I have three class with same functions in it, which I am calling. I put these functions into utils.py file ad just used there names in context after importing them in my views. In those functions I am using the models to get the data, I have imported them in utils but after all this it raises an error **ModuleNotFoundError: No module named 'pageflows.website' ** I don't get it why this error occured? Kindly help me out in this. I don't get it why this error occured? Kindly help me out in this. -
Celery picks up new tasks, but all old are stuck in PENDING
In a nutshell: I'm able to run new celery tasks but the old ones are stuck with PENDING states. Celery run command: celery -A config.celery_app worker --pool=solo --loglevel=info Environment: Celery 5.4.0 redis-server 7.4.1 on WSL (Windows Linux) The celery and Django app runs on windows and the redis-server in WSL. I ran celery a couple of times and everything was good, but now I constantly see some old tasks as "PENDING" state when I read their state in Django with AsyncState(task_id). Purging the queue with celery -A config.celery_app purge didn't make anything either. I visited a couple of threads on this, but none seem to be dealing with my precise problem. (I'm still able to execute new tasks) I wonder if it's not a problem with running on WSL or something like this, because I'm also unable to see the task queues from the app or CLI: celery inspect active_queues gives kombu.exceptions.OperationalError: [WinError 10061] No connection could be made because the target machine actively refused it and doing: i = app.control.inspect() scheduled = i.scheduled() shows no tasks Project is built with django-cookiecutter and Celery task was basically defined as: @app.task def my_task(**kwargs): return my_function(**kwargs)