Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
direnv cannot find .envrc file even it does exist
I set up a virtual environment for a Django-React project. I have created the .bashrc in the user home directory, and .envrc file in the root folder of the project repo. But when I tried 'direnv allow' it always return '.envrc does not exit' with a weird referenced folder path. Can someone please help? direnv allow error direnv status I'm doing it on Windows 11. I tried to re-install everything and change the position of the folder from E to C driver. I also tried to rename the folder to anything else to see if any of it results in the weird folder path. But the error message remains. -
create seperate radio button using djang forms
I am trying to create radio buttons using modelform. The problem I'm having is that I can't get the radio buttons to separate, and it's also displaying a blank field. Here is what i am saying . Here is the html code for this one. <div id="cid_68" class="form-input jf-required"> <div class="form-multiple-column" data-columncount="2" role="group" aria-labelledby="label_68" data-component="radio"> <span class="form-radio-item" > <span class="dragger-item"></span> <!-- <input type="radio" aria-describedby="label_68" class="form-radio validate[required]" id="input_68_0" name="q68_typeA68" value="staff" required="" onclick="myFunction(0)"/> <label id="label_input_68_0" for="input_68_0">Staff</label> --> {{form.designation}} </span> <span class="form-radio-item"> <span class="dragger-item"></span> <!-- <input type="radio" aria-describedby="label_68" class="form-radio validate[required]" id="input_68_1" name="q68_typeA68" value="student" required="" onclick="myFunction(1)"/> <label id="label_input_68_1" for="input_68_1">Student</label> --> </span> </div> </div> </li> Here's what i want to achieve models.py DESIGNATION = ( ("Staff", "Staff"), ("Student", "Student"), ) class User(AbstractUser): username = models.CharField(max_length=9, default="", unique=True) avatar = models.ImageField( blank=True, null=True, default="avatar.svg", upload_to="images", validators=[validate_pic_extension]) password2 = models.CharField(default="", max_length=128, verbose_name="Confirm Password", null=True, blank=True,) email = models.EmailField(default="", max_length=255, unique=True) designation = models.CharField(default="", choices=DESIGNATION, max_length=255, null=True, blank=True) staff_id = models.CharField(default="", max_length=255, null=True, blank=True, verbose_name="Staff Id") matric_no = models.CharField(default="", max_length=255, null=True, blank=True, verbose_name="Matric Number") lib_user = models.CharField(default="", max_length=255, choices=LIBUSER, null=True, blank=True, verbose_name="Library User") library_id = models.CharField(default="", max_length=255, null=True, blank=True, verbose_name="Library Card Id") def __str__(self): return self.username forms.py class Profile(forms.ModelForm): class Meta: model = User fields = [ "username", … -
How to write testcase for django apis which has jwt?
I have python django project which has jwt implemented. And otp system and hash implementation for verifying email so any to write test cases for it. I dont want to test every models and serializers. Just want to test api end points if its working or not If anyone has any kind of example of it can share please -
Trouble Inheriting a function that renders data in a class containg a django generic view
First, I have model (Entry), where one field, 'prompt', is where I want to store text, "You suck bro!", in my django admin database. The second field, 'body', is a text editor I want to show on my html page. enter image description here In my views file, I have a function: def indexx(request), which renders text from the admin database, field 'prompt' on to my html page. views.py def indexx(request): entry = Entry.objects.all() return render(request, "entries/entries.html", {"ents" : entry}) urls.py from django.urls import path from .views import indexx urlpatterns = [ path("", indexx) ] This only renders text from django models: field ('prompt'). enter image description here Next, in my views file, I have a class, class EditEntryView(CreateView), where "(CreateView)", from "django.views.generic import CreateView". This allows me to render the text editor on my html page. The vies and urls are under the same python files as well. views.py class EditEntryView(CreateView): model = Entry # form_class = PostEntry fields = ["body" ] template_name = "entries/entries.html" urls.py from django.urls import path from .views import EditEntryView urlpatterns = [ path("", EditEntryView.as_view(), name="entries") ] This class renders the text editor. enter image description here My goal is to render the two separate … -
Difference between icontains and iregex in django
I am looking for solution of an usecase where i need to return search results even for part of a matching input text ex: if input text is man and the data that we have is ["manmohan", "manchester", "map"], then i should be returning ["manmohan", "manchester"] i was searching across the net on how to implement it using django, and saw two probable methods, icontains and iregex my questions here are which suits my usecase? what is the difference between these 2? -
Heroku deployment of django project causing: Exception Type: ProgrammingError
I have tested this locally and it works fine. When I deploy to Heroku it deploys fine and serves the home page. Though When I try to sign up and create a new user I get a Internal 500 error and get the following error message. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (relation "accounts_customuser" does not exist LINE 1: SELECT 1 AS "a" FROM "accounts_customuser" WHERE "accounts_c... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/edit.py", line 152, in post if form.is_valid(): File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 205, in is_valid return self.is_bound and not self.errors File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 200, in errors self.full_clean() File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 439, in full_clean self._post_clean() File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/forms.py", line 129, in _post_clean super()._post_clean() File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/models.py", line 498, in _post_clean self.validate_unique() File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/models.py", line 507, in validate_unique self.instance.validate_unique(exclude=exclude) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1226, in validate_unique errors = … -
Is it a django rest framework good practise?
I am developing a restaurant management system where there are 4 types of user : admin, chef, driver (who delivers food) and the customer, and i am using django rest framework to create my restful api. Howeve I am stuck at the authentication process, since django doesn't have multiple users, i've read a lot of tutorials and stackoverflow questions and answers including : How to implement multiple user types with different roles and permissions in Django? How to Implement Multiple User Types with Django django best approach for creating multiple type users Creating multiple user types and using proxy models I didn't want to use the proxy model, since i didn't want to violate django rule for no multiple users, so i've created my solution but i want to know if it is good or bad or violate some good practises and if it will cause me headaches in the Future. models.py file : class UserRoles(models.TextChoices): ADMIN = 'admin', 'Admin' CUSTOMER = 'customer', 'Customer' CHEF = 'chef', 'Chef' DRIVER = 'driver', 'Driver' class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) is_admin = models.BooleanField(default=False) role = models.CharField(max_length=50, choices=UserRoles.choices) is_customer = models.BooleanField(default = False) is_chef = models.BooleanField(default … -
InterfaceError: cursor already closed
We have a Django 4.0.4 site running. Since upgrading from Python 3.10->3.11 and Psycopg2 from 2.8.6->2.9.3/5 and gunicorn 20.0.4->20.1.0 we've been getting random InterfaceError: cursor already closed errors on random parts of our codebase. Rarely the same line twice. Just kind of happens once every 5-10k runs. So it feels pretty rare, but does keep happening a few times every day. I've been assuming it's related to the ugprade, but it may be something else. I don't have a full grap on why the cursor would be disconnecting and where I should be looking to figure out the true issue. Psycopg version: 2.9.5 & 2.9.3 Python version: 3.11 PostgreSQL version: 12.11 Gunicorn The site had been running for 1-2 years without this error. Now it happens a few times every day after a recent upgrade. -
Django 4 - TransactionTestCase - Postgresql sqlflush error
My code: Django 4.1 I am using multiple postgresql schemas for my models, postgresql12 with out-of-box ubuntu 20.04 setup. I am performing unit tests of some code which uses transactions. migrations are created When running other non-transaction tests with django TestCase, everything works normal. When running transaction test with TransactionTestCase (even with empty test function), this happens: django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "users_user_permissions" references "auth_permission". HINT: Truncate table "users_user_permissions" at the same time, or use TRUNCATE ... CASCADE. ... django.core.management.base.CommandError: Database test_mike3 couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. django-admin sqlflush: BEGIN; TRUNCATE "django_content_type", "auth_group_permissions", "django_session", "auth_group", "auth_permission", "django_admin_log" RESTART IDENTITY; COMMIT; My solution I have gone into code and added _fixture_teardown(self) override to my ExampleTestCase(TransactionTestCase): basically changed allow_cascade=True in flush command. Since by this documentation: https://docs.djangoproject.com/en/4.1/topics/testing/advanced/ not setting available_apps might cause memory leaks, I will probably set all my apps to it so allow_cascade is set to True automatically. Original django … -
How to I get ForeignKey and M2M Django Ninja when making a post request
Am expecting to input the album_id which is a ForeignKey to my Music model and also the genres which is a ManyToManyField to the Music model also. This how I setup the Schema through the create_schema from ninja.orm from ninja import ModelSchema, Schema, Field from ninja.orm import create_schema from .models import Music MusicSchemaIn = create_schema(Music, name="MusciSchemaIn", exclude=['id', 'song_duration', 'slug', 'page_view', 'created'], base_class=Schema) This is my code for making a post request # upload music @router.post('/musics') def create_music(request, data: MusicSchemaIn): music = Music.objects.create(**data.dict()) return {'id': music.id} The error I get when a make a post request using the ModelSchema I created. Traceback (most recent call last): File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\ninja\operation.py", line 99, in run result = self.view_func(request, **values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\punga_play\music\views.py", line 22, in create_music music = Music.objects.create(**data.dict()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\query.py", line 669, in create obj = self.model(**kwargs) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\base.py", line 541, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 237, in __set__ raise ValueError( ValueError: Cannot assign "0": "Music.album" must be a "Album" instance. -
Celery alternative for very long running tasks
I'm searching for an alternative for Celery to process heavy long-running tasks (24 hrs +). Currently I'm using django + celery + redis, but I'm always running into strange behavior like that the worker simply freezes and does not consume tasks anymore ... Now I'm searching for something that is more designed to handle extremely long-running tasks for video conversion. Can anyone provide some advice, what might be the best choice here? I also need to be able to spin up periodic tasks. Thanks in advance -
How can I Log In user automatically after checking comparing user.email_verification_token?
My idea is to call LoginUser after checking user.email_verification_token == token and pass user's email and password, but there is a problem because I don't how to pass them as instance of django.http.HttpRequest. Could you help me guys? @api_view(['POST']) def verify_email(request, pk, token): try: user = User.objects.get(id=pk) except User.DoesNotExist: raise AuthenticationFailed('User not found!') if user.expiration_date < timezone.now(): return AuthenticationFailed('expired_token') if user.email_verification_token == token: user.is_email_verified = True user.save() return Response('message: success') return Response('message: Verification Rejected') @api_view(['POST']) def LoginUser(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') ........ ........ -
Django not showing up all fields using objects with select_related
i'm facing an annoing bug in Django and i don't know how i can solve it. I'm trying to show up names from one other table using INNER JOIN but isn't working. Just to clarify, i have two database canaisAssoc and formatosAssoc, i'm trying to show up from canaisAssoc the name of the canais and from formatosAssoc the name of the formato, if you take a look at my views.py, i'm using ajax, because i need to choose one value from one select in template to fill up others, the issue is, when i run the canaisAssoc.objects.select_related('idCanal').filter(idSite_id = site, ativo = True).all() if i run this print(channels.query) The return of the query is: SELECT campanhas_canaisassoc.id, campanhas_canaisassoc.idSite_id, campanhas_canaisassoc.idCanal_id, campanhas_canaisassoc.ativo, campanhas_canais_dados.id, campanhas_canais_dados.nomeCanais, campanhas_canais_dados.ativo FROM campanhas_canaisassoc INNER JOIN campanhas_canais_dados ON (campanhas_canaisassoc.idCanal_id = campanhas_canais_dados.id) WHERE (campanhas_canaisassoc.ativo = True AND campanhas_canaisassoc.idSite_id = 3) If i run this in phpMyAdmin, they are working as expected, showing up all values i'm need it id|idSite_id|idCanal_id|ativo|id|nomeCanais|ativo However, if i inspect the call of JSON, they are returning this: {"channel": [{"model": "campanhas.canaisassoc", "pk": 14, "fields": {"idSite": 3, "idCanal": 13, "ativo": true}}, {"model": "campanhas.canaisassoc", "pk": 15, "fields": {"idSite": 3, "idCanal": 1, "ativo": true}}, {"model": "campanhas.canaisassoc", "pk": 16, "fields": {"idSite": 3, "idCanal": … -
Create Django objects in step increments
I'm trying to write a function to create total number of Django objects in step increments. Note, I'm using factory-boy to generate the fake data. Here is what I have come up with: def create_todos_in_batch(total, step): quotient, remainder = divmod(total, step) for i in range(quotient): print(f"Inserting {i * step:,} to {(i + 1) * step:,}") todos = TodoFactory.build_batch(step) Todo.objects.bulk_create(todos) if remainder: print(f"Inserting {total - remainder:,} to {total:,}") todos = TodoFactory.build_batch(remainder) Todo.objects.bulk_create(todos) To create 100 objects in 20 object increments, the function can be called like so: create_todos_in_batch(100, 20) I have the following unit test to prove this works correctly: @pytest.mark.parametrize( "total, step", [ (100, 20), (1_000, 100), (10_000, 1_000), ], ) @pytest.mark.django_db def test_create_in_batch(total, step): create_todos_in_batch(total=total, step=step) count = Todo.objects.count() assert count == total, f"{count:,} != {total:,}" Is there a better way to write this function? I feel like this is too verbose because I'm repeating TodoFactory.build_batch() and Todo.objects.bulk_create(todos) multiple times. -
Is it possible to use Django's Replace in a case-insensitive way?
With a query like this: from django.db.models import Value from django.db.models.functions import Replace MyModel.objects.update(description=Replace("description", Value("old"), Value("new"))) Django will have the database search for the substring old in the description field, and replace it with new. Is it possible to also match oLd, and OLD, etc without explicitly specifying each combination? Have Replace look for old with any case, and replace it with the new string? The documentation for Replace doesn't seem to specify a case insensitive option. -
Html bootstrap template
I was using a bootstrap template to create a website, I'm now stuck cause I was trying to edit the text's color and font, I did every thing you're supposed to do in html when editing a text but when I refresh the page nothing changes. The image I added should be of help I added the html styling in the div of the text, and I expected the font and color of the text to changeI added the image to help -
DB not being reacheable using tox command in django project
I am having an issue running test inside my django application which is running inside of a container. I have a tox.ini file: [vars] PROJECT = django_project TASKS = tasks [tox] envlist = py310, flake8, black, mypy [testenv] deps = -rrequirements.txt -rrequirements-dev.txt commands = python manage.py test [testenv:flake8] basepython=python3 deps = -rrequirements-dev.txt commands= python3 -m flake8 --max-line-length=100 {[vars]PROJECT} {[vars]TASKS} whitelist_externals = /usr/bin/python3 [testenv:black] deps = -rrequirements-dev.txt commands = black --check --diff {[vars]PROJECT} {[vars]TASKS} [testenv:mypy] deps = -rrequirements-dev.txt commands = mypy --install-types --non-interactive \ --ignore-missing-imports \ --disallow-untyped-defs \ --disallow-incomplete-defs \ --disallow-untyped-decorators {[vars]PROJECT} {[vars]TASKS} Which runs fine for all the stages except for testenv. I am getting an output: psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known Eventhough when I run the command python manage.py test inside CLI, it works without erros. Anyone has idead what this could be causing? I am quite new to seting up things with tox. -
Django changing date format is not working
I decided to change the date format from YYYY-mm-dd to %d %b %Y something like 10 Jan 2023 However, i have tried many things and it all seem to fail, let's start with settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = False USE_TZ = True USE_L10N = False DATE_FORMAT ='%d %b %Y' the model: class DateModel(models.Model): date = models.DateField(auto_add_now=True,blank=False) desc = models.CharField() the serializer: from appname import models class DateSerializer(serializer.ModelSerializer): class Meta: model = models.DateModel fields = '__all__' # alternatively 'date','desc', the view: from rest_framework import views from appname import serializer #importing the serializer file from django.utils import timezone,dateformat from appname import models from django.conf import settings class DateView(views.APIView): serializer_class = serializer.DateSerializer def get(self,request): return Response(serializer.DateSerializer(models.DateModel.objects.all().data),status=200) def post(self,request): data = serializer.DateSerializer(data=request.data) if data.is_valid(): desc = data.data['desc'] date = dateformat(timezone.now(),settings.DATE_FORMAT) model_instance = models.DateModel.objects.create(date=date,desc=desc) model_instance.save() return Response("Posted!",status=200) return Response("Invalid Data, 400 status code error is raised",status=400) and when i submit a post and try to view it, i get the date in this format 2023-01-10, as i mentioned before, but i am aiming for this format 10-Jan-2023 -
Find and delete similar records in Postgres
TL\DR version - Find and delete rows in Postgres with same date but different time, leaving one record per date. Long read: At some point we've migrated our app's backend to a newer version - this is a Django application - migrated from Python 2, Django 1.8 to Python 3 - Django 4, and with this update we're changed timezone for backend from UTC+2 to UTC+3. And now strange things happens - records which previously successfully have been read from db with queryset StatChildVisit.objects.filter(date=day, garden_group=garden_group) - (day is a python's date only not datetime) after update returns empty queryset, although records for that day are still in db. More so newly created records have different time in them - records created with old timezone looks like 2022-12-28 22:00:00.000000 +00:00 new records looks like 2022-12-28 21:00:00.000000 +00:00 Seems that bug happened because date field in django's model have been declared as DateTimeField - class StatChildVisit(models.Model): child = models.ForeignKey(Child, on_delete=models.CASCADE) date = models.DateTimeField(default=timezone.now) visit = models.BooleanField(_('Atended'), default=True) disease = models.BooleanField(_('Sick'), default=False) other_approved = models.BooleanField(_('Other approved'), default=False) garden_group = models.ForeignKey(GardenGroup, verbose_name=_('Garden group'), editable=False, blank=True, null=True, on_delete=models.CASCADE) rossecure_visit = models.ForeignKey('rossecure.Visits', editable=False, null=True, blank=True, on_delete=models.CASCADE) class Meta: verbose_name = _('Attendence') verbose_name_plural = _('Attendence') index_together = … -
NoReverseMatch Reverse for 'by_person' with arguments '('',)' not found. 1 pattern(s) tried: ['people/person/<int:person_pk\\Z']
Cde from template {% extends 'laayout/basic.html' %}your text {% block content %} Главная {% for per in people %}`your text` <h1><a href="{% url '>{{ per }}</a></h1> {% endfor %} {% endblock content %} Code from urls: urlpatterns=[ path('person/<int:person_pk',by_person,name='by_person'), path('',people,name='people'), ] i tried to fix but i got more issues -
scrape hundreds of amazon affiliate links via ASIN using python
I am working on a django project. At the moment i have a postgres database where all my products including their ASIN are stored. In the next step i need the affiliate link for each product. I thought about two options. What do you think is the better one and why? 1.) Using the AWS Product Advertising API (already have it) and generating each affiliate link seperately 2.) If i understood it correctly, there is a way to link my website to aws in such a way, that everytime someone comes from my website, my partnerlink will be added automatically -
Django as Backend and Weblfow as frontend?
I can code and I want to build a SaaS with Python Django but I want to use Django as the backend and for the front end, I want to use Webflow. Is it a good idea? If not what would you suggest? -
Django Channels is not taking over deployment server
I am attempting Django Channels for the first time. I am following this tutorial - https://www.youtube.com/watch?v=cw8-KFVXpTE&t=21s - which basically explains Channels basics. I installed Channels in my virual environment using pip install channels and it installed the latest version, which is 4.0.0. I have laid out the basic setup. But when I run python manage.py runserver, I get - Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 10, 2023 - 02:37:40 Django version 4.1.3, using settings 'BrokerBackEnd.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. when I shoul be getting this - Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 10, 2023 - 02:37:40 Django version 4.1.3, using settings 'BrokerBackEnd.settings' Starting ASGI/Channels version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. I cannot figure out what I might be doing wrong here and I cannot find any relevant solution anywhere. I would really appreciate any suggestions anyone might have. settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'Orders', ] ASGI_APPLICATION = "BrokerBackEnd.asgi.application" asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, … -
"django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" when run Celery
I'm trying to install celery in my docker-compose project. When I execute docker-compose up I obtain this log: project_meals_celeryworker | ERROR 2023-01-09 20:29:06,089 signal 11 274910545088 Signal handler <bound method DjangoFixup.on_import_modules of <celery.fixups.django.DjangoFixup object at 0x4004f385e0>> raised: ModuleNotFoundError("No module named 'food'") project_meals_celeryworker | Traceback (most recent call last): project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/utils/dispatch/signal.py", line 276, in send project_meals_celeryworker | response = receiver(signal=self, sender=sender, **named) project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/fixups/django.py", line 82, in on_import_modules project_meals_celeryworker | self.worker_fixup.validate_models() project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/fixups/django.py", line 120, in validate_models project_meals_celeryworker | self.django_setup() project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/fixups/django.py", line 116, in django_setup project_meals_celeryworker | django.setup() project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/django/init.py", line 24, in setup project_meals_celeryworker | apps.populate(settings.INSTALLED_APPS) project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate project_meals_celeryworker | app_config = AppConfig.create(entry) project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 193, in create project_meals_celeryworker | import_module(entry) project_meals_celeryworker | File "/usr/local/lib/python3.9/importlib/init.py", line 127, in import_module project_meals_celeryworker | return _bootstrap._gcd_import(name[level:], package, level) project_meals_celeryworker | File "", line 1030, in _gcd_import project_meals_celeryworker | File "", line 1007, in _find_and_load project_meals_celeryworker | File "", line 984, in _find_and_load_unlocked project_meals_celeryworker | ModuleNotFoundError: No module named 'food' project_meals_celeryworker | ERROR 2023-01-09 20:29:06,096 signal 11 274910545088 Signal handler <promise@0x4004ebaee0 --> <bound method Celery._autodiscover_tasks of <Celery main at 0x4004ed1130>>> raised: AppRegistryNotReady("Apps aren't loaded … -
Django , map sql output with different values using dictionary and send them to template
I have a function that I use to show number of citizens and countries in charts.js def Inbound_top_20(request): cursor1=connections['default'].cursor() // calling default database connection cursor1.execute("select citizens, countries from world ") r1=dictfetchall(cursor1) // calling dictfetchall function , because I use raw sql D1={"1-1":"France" , "2-2":"Spain" , "3-3":"Germany",.....} //dictionary return render(request,'app_sins/countries .html',{"show1" : r1,"D1": D1,}) output of query are values of citizens, and name of countries, but countries are represented as string "1-1" , "2-2" , "3-3". I wish to map SQL output for countries using dictionary D1, to give them real names , not strings "1-1" or "2-2" ... After that I need to vizualize them through the charts.js. Below is extract from charts.js using column countries which works fine for strings ("1-1" or "2-2" ...) ...... const ctx11 = document.getElementById('myChart11').getContext('2d'); const myChart11 = new Chart(ctx11, { type: 'line', data: { labels: [{% for show1 in show1%} '{{show1.countries}}', {% endfor %}], ......... Please advise how I can easily map sql output strings ("1-1" or "2-2" ...) to real names and put them in template tags