Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin all users's permissions
Groups: Users: In django admin I can only see user's permissions, but I want to see all user permissions, including group permissions. So in the right column it would display all permission of selected user. I can get list of all permissions via user.get_all_pemissions, but I can not display it there. Only thing that i succeded with is to display them like this: I understand that i can not remove group permission from user, but at least I want to display them more prettier. -
Nested Serializer for prefect_related in Django Rest Framework
I'm trying to make a nested serializer with prefect_related but it doesn't work, here's my code: models.py from django.db import models class Student(models.Model): phone = models.IntegerField(null=True) birth_date = models.DateField(null=True) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="student") class Course(models.Model): title = models.CharField(max_length=100, blank=True, default='') class CourseEnroll(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT, related_name='course_enroll') student = models.ForeignKey(Student, on_delete=models.PROTECT, related_name='student_enroll') views.py from rest_framework import mixins from rest_framework.viewsets import GenericViewSet from quiz.models import Course from quiz.serializers import CourseSerializer class CourseViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): def get_queryset(self): queryset = Course.objects.prefetch_related("course_enroll").all() return queryset serializer_class = CourseSerializer serializers.py from rest_framework import serializers from quiz.models import Course, CourseEnroll class CourseEnrollSerializer(serializers.ModelSerializer): class Meta: model = CourseEnroll fields = ['id'] class CourseSerializer(serializers.ModelSerializer): student_enrolled = CourseEnrollSerializer(many=True, read_only=True) class Meta: model = Course fields = ['id', 'title', 'student_enrolled'] Here's my repo: https://github.com/ncson1/regov-pop-quiz-backend-s-v1/tree/main/quiz Did I do something wrong here? Please help, thanks. -
Can I host a Django CMS everywhere?
Somehow I cannot find the one simple answer if I can host Django CMS at "common" hosting providers. As Django is python I assume this is not possible and I need specific python hosting. Am I correct? -
TypeError at /uploadimage/ expected str, bytes or os.PathLike object, not tuple
I'm trying to upload a text and an image to an SQL database but I get that error... views.py def home_view(request): context = {} if request.method == "POST": form = ImagefieldForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data.get("name") img = form.cleaned_data.get("image_field") obj = ImagefieldModel.objects.create( title = name, img = img ) obj.save() print(obj) return HttpResponse('successfully uploaded') else: form = ImagefieldForm() context['form'] = form return render( request, "fileupload.html", context) model.py class ImagefieldModel(models.Model): title = models.CharField(max_length=200) img = models.ImageField(upload_to="images/") class Meta: db_table = "imageupload" How can I solve this problem? -
Failed when running Python manage.py migrate
fn(*args, **kwargs) File "C:\Users\ASUS\project\django_ecommerce_2020\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ASUS\project\django_ecommerce_2020\env\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\ASUS\project\django_ecommerce_2020\saleor-main\saleor\plugins\apps.py", line 20, in ready self.load_and_check_plugin(plugin_path) File "C:\Users\ASUS\project\django_ecommerce_2020\saleor-main\saleor\plugins\apps.py", line 26, in load_and_check_plugin raise (ImportError(f"Failed to import plugin {plugin_path}: {e}")) ImportError: Failed to import plugin saleor.plugins.avatax.plugin.AvataxPlugin: failed to find libmagic. Check your installation Django error --python manage.py migrate`your text` Failed to import plugin saleor.plugins.avatax.plugin.AvataxPlugin:` -
how to authorize user after storing jwt tokens in the local storage?
settings.py """ Django settings for auth project. Generated by 'django-admin startproject' using Django 4.1.5. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from datetime import timedelta 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/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-iogl-doj_#_npx4ss#7mn4!x0zn$gjn!&o7a1=m!u_vf#$_9fi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'djoser', 'authorize', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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 = 'auth.urls' CORS_ORIGIN_ALLOW_ALL = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'auth.wsgi.application' AUTH_USER_MODEL = 'authorize.User' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'authdb', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': … -
Reactivesearch not getting data from elasticsearch on localserver
I am building an app using Django, React and ElasticSearch. The data is sent from Django models to elasticsearch on localhost and I want to use Reactivesearch to display my search results. I have the following component according to the documentation: export default function LandingPage(){ return ( <ReactiveBase url="http://localhost:9200" app="entries" credentials="AUTH_CREDENTIALS" headers={{ secret: 'reactivesearch-is-awesome' }} > <SearchBox componentId="SearchBoxSensor" dataField={[{ 'field': 'title', 'weight': 1 }, { 'field': 'body', 'weight': 2 } ]} /> {/* Our components will go over here */} Hello from ReactiveSrch 👋 </ReactiveBase> ) } in elasticsearch.yaml: http.cors.enabled: true http.cors.allow-origin: '*' http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE http.cors.allow-headers: X-Requested-With, X-Auth-Token, Content-Type, Content-Length, Authorization, Access-Control-Allow-Headers, Accept http.cors.allow-credentials: true I found that Reactive search doesn't access the elasticSearch data and I find this in my console I have tried to change http.cors.allow-origin: '*' in elasticsearch.yaml to http.cors.allow-origin: /https?:\/\/(localhost)?(127.0.0.1)?(:[0-9]+)?/ according to what I have found in this question Also I have tried to test the API using fetch outside ReactiveSearch component and It worked and data is displayed to me. So how can I access my elasticsearch data using Reactivesearch on my localserver? -
Django Admin don't call `_get_FIELD_display`
I have overridden the _get_FIELD_display in my model in it's used correctly in the serializers however, the Django admin apparently doesn't call it The model class X(TimeStampedModel): STATUSES = Choices( ("PENDING", _("Pending")), ("PLACED", _("Placed")), ("SHIPPED", _("Shipped")), ("DELIVERED", _("Delivered")), ) status = FSMField(default=STATUSES.PENDING, choices=STATUSES, protected=True) def get_status_display(self) -> str: """ Overrides to replace Order.STATUSES.DELIVERED with Completed as it's confusing.""" value = self.status if value == Order.STATUSES.DELIVERED: return _("Completed!") choices_dict = dict(Order.STATUSES) # force_str() to coerce lazy strings. return force_str(choices_dict[value], strings_only=True) -
Have you ever see this problem on Django : frozen importlib._bootstrap
(env) PS C:\Users\wolf\Desktop\DashBoardv2\DashBoardv2> python manage.py migrate Traceback (most recent call last): File "C:\Users\wolf\Desktop\DashBoardv2\DashBoardv2\manage.py", line 22, in <module> main() File "C:\Users\wolf\Desktop\DashBoardv2\DashBoardv2\manage.py", line 18, in main self.models_module = import_module(models_module_name) self.models_module = import_module(models_module_name) File "C:\Users\wolf\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 879, in exec_module File "<frozen importlib._bootstrap_external>", line 1017, in get_code File "<frozen importlib._bootstrap_external>", line 947, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Hello, I created a project in django. And after having created my connection with my database and a router.py because I use a router page as I have databases. I don't use bootstrap in my project that's why I'm surprised to have this error that I don't understand and that I haven't been able to pass for several hours already! Je suis française si vous voulez répondre en français c'est avec plaisir ! Sinon je prends l'anglais aussi ! -
How to connect Django app hosted on heroku with redis (Heroku addon)
`config worker error 1)i have a celery worker and a beat which needs Redis as a broker , in my local environment i am able to connect to redis local host using and i am able to recieve the beat results as i needed 2)now when i wanted the redis to be the heroku addon so i followed this article https://devcenter.heroku.com/articles/connecting-heroku-redis#connecting-in-python and placed this code the config code as can be seen in the image in my settings.py file and started my worker as can be seen in worker image, after which is the output which i am getting can be seen in the error image` -
NoReverseMatch at /login.html/
this is the html form. I added action="{% url 'create_user_view' %}" to the html but the error says it is not a valid view. {% extends 'base.html' %} 2 3 {% block content %} 4 5 6 <div class="formbox"> 7 <form method="post" action="{% url 'create_user_view' %}"> 8 <h1 class="max"> Sign up </h1> 9 <input type ="text" class="max" id="fname" placeholder="username" name="username"> 10 <br> 11 <input type="email" class="max" id="email" placeholder="email" name="email"> 12 <br> 13 <input type="password" class="max" id="password" placeholder="password" name="password"> 14 <br> 15 <input type="submit" name="submit" class="max" placeholder="SUBMIT" id="submitid" formaction="logbook.html"> 16 <br> 17 <a href="home.html" id="links">already have an account?</a> Given below is the views.py file. I have created a view called create_user_view in the views.py file. However, the html form action does not find a valid view called create_user_view. from django.shortcuts import render from django.contrib.auth.models import User from django.shortcuts import render, redirect # Create your views here. def home_screen_view(request): print(request.headers) return render(request, "personal/home.html",{}) def login_view(request): print(request.headers) return render(request,"personal/login.html",{}) def create_user_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user = User.objects.create_user(username=username, password=password, email=email) # You can add additional fields to the User model as needed # Redirect to a success page return redirect('success') # If the request … -
Django migrations: when deploying on AWS ECS cluster
I have a djanog application. I have created an Docker image and pushed to ECR My docker image, has an entryscript which runs the python manage.py migrate I am planning to have a 4 tasks/containers of DJango running simultaneously So when each container is getting started, it will run the entrypoint script. Assume two containers are starting in parallel, each will try to run the entrypoint script. i.e the migrate So I am thinking this will collide with the database tables creation properly How to solve this issue -
Upload image to MongoDB from django rest api
I'm trying to set an api endpoint who get an image and send it to my mongodb database. I'm using djangorest api to create the endpoint. I tried to set my class image in my model like : from django.db import models from utils import database class Image(models.Model) : name = models.CharField(max_length=255) description = models.TextField(blank=True) image = models.ImageField(upload_to=database.post_image) but as you can expect upload_to=database.post_image doesn't work at all, because upload_to expect str, bytes or os.PathLike object, not NoneType. Do you have any idea? thanks you -
Run a django-admin command for a set duration inside of a test
Problem The test runs a django-admin command in a thread with a timeout. The test passes, but it hangs and I must manually stop its execution. I'm not familiar with threading, but I think the thread keeps running, which causes the test to "hang" after it passes. I'm looking for a solution that runs the command since this is more of an integration test and not a unit test with mocks. Any solution that runs the command for a set duration should work as long as there's proper test teardown and it doesn't cause issues for other tests during CI. Background Django-pgpubsub listens for PostgresSQL triggers by running python manage.py listen. I'm using this as a lightweight alternative to Django signals and celery for sending emails when a Shipment model instance's status field changes to specific values. The Test # transaction=True is needed listen command to work for django-pgpubsub @pytest.mark.django_db(transaction=True) def test_shipment_status_notifications_with_listen_command(testuser): user = testuser notification_settings = NotificationSettings.objects.get(user=user) notification_settings.failed_attempt = True notification_settings.save() cust_email = "test@somedomain.com" customer = Customer.objects.create(email=cust_email) order = Order.objects.create(customer=customer) def run_listen_command(): call_command("listen") listen_thread = threading.Thread(target=run_listen_command, daemon=True) listen_thread.start() # Change Shipment status to trigger the notification shipment = Shipment.objects.create(user=user, order=order) shipment.status = Shipment.FAILED_ATTEMPT shipment.save() sleep(1) # required to allow … -
Where do i paste my app password in django app?
Im trying to send email through my form in django application so i generated app password: somethingsomethi (for example) where do i paste it in my code? EMAIL_HOST_USER = 'something@gmail.com' EMAIL_HOST_PASSWORD = 'Something' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
Get Count of entries in all tables in database using django
Without mentioning the tables can i get count of entries in each table using django ORM. Don't want to use count() against each table manually. -
Why staticfiles aren't found when DEBUG=False (in production)?
This is django app and I am using DigitalOcean App platform for deploying my app. When I set DJANGO_DEBUG=True (in the enviroment veriables on DigitalOcean) all the static files are found by the server and my app works fine. BUT when I set DJANGO_DEBUG=False, then everything goes wrong: I get 500 error code When I checkout the "Runtime logs" there is the same error message: **ValueError: Missing staticfiles manifest entry for 'images/favicons/favicon.ico'** [gumroad-clone] [2023-04-04 09:20:11] [gumroad-clone] [2023-04-04 09:20:11] During handling of the above exception, another exception occurred: [gumroad-clone] [2023-04-04 09:20:11] [gumroad-clone] [2023-04-04 09:20:11] Traceback (most recent call last): [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner [gumroad-clone] [2023-04-04 09:20:11] response = get_response(request) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/utils/deprecation.py", line 134, in __call__ [gumroad-clone] [2023-04-04 09:20:11] response = response or self.get_response(request) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 58, in inner [gumroad-clone] [2023-04-04 09:20:11] response = response_for_exception(request, exc) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception [gumroad-clone] [2023-04-04 09:20:11] response = handle_uncaught_exception( [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 185, in handle_uncaught_exception [gumroad-clone] [2023-04-04 09:20:11] return callback(request) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapped_view [gumroad-clone] [2023-04-04 09:20:11] response = view_func(request, *args, **kwargs) [gumroad-clone] [2023-04-04 09:20:11] File "/workspace/.heroku/python/lib/python3.10/site-packages/django/views/defaults.py", line 102, in … -
How can the Django ORM perform an aggregate subquery in a WHERE statement?
I'm trying to construct the following query similar to this the Django ORM: SELECT * FROM table WHERE depth = (SELECT MIN(depth) FROM table) How can this be written in Django ORM notations? So far it seems hard to use an aggregate like this, because QuerySet.aggregate() isn't lazy evaluated, but executes directly. I'm aware that this basic example could be written as Model.objects.filter(depth=Model.objects.aggregate(m=Min('depth'))['m']) but then it does not evaluate lazily, and needs 2 separate queries. For my more complex case, I definitely need a lazily evaluated queryset. Any attempt to use .order_by().values().annotate(m=Min('depth').values('m') will result in a GROUP BY id that seems hard to loose. Also using Model.objects.annotate(m=Min('depth')).filter(depth=F('m')) will give a GROUP BY id, and include the m value in the main results as that's what annotate does. So far I've worked around this case by using QuerySet.extra(where=[...]) but I'd much rather like to see the ORM generate that code. -
Memory grows when using allow_join_result
I have two celery apps in my environment that are : app1 = Celery('app1', broker=BROKER_URL1, backend=BROKER_URL1) app2 = Celery('app2', broker=BROKER_URL2, backend=BROKER_URL2) From a django app within a web container I call a task in app1. That task needs to call a task within app2 and wait for its result. @app1.task() def task_app1(some_list): results = [] for i in some_list: with allow_join_result: task = app2.send_task('task_app2',kwargs={"id": i}) result = task.get() # This returns a relatively large JSON results.append(Result(r1=result["r1"], r2=result["r2"])) # Result is a Django model Result.objects.bulk_create(results) I noticed celery won't release memory after fetching result and instead it will grow infinitely. When i subtitute the result variable with a static JSON (or just read the JSON from a file), i don't experience that issue - that proves to me that the issue is not with the results list. How can i ensure Django "forgets" each indivdual call to app2? I tried del result, del task and gc.collect() too. -
Unable to open secure websocket connections in Django Rest Framework
Following is my asgi, which worked perfectly fine for normal websocket connection ws:// But it fails when the frontend tries to open secure websocket connection via wss:// Kindly let me know what needs to be done. application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) -
Use Column Value as key and another Column Value as dict from django ORM
In Django, I am trying an output without using a for loop to optimise the operation. My model structure seems like this class Test(BaseClass): id = model.UUIDField(uniq=True) ref = models.ForeignKey(Ref) name = model.CharField(max_length=50) Sample data in the table +--------------------------------------+--------+----------------+ | id | ref_id | name | +--------------------------------------+--------+----------------+ | 412dacb1-6451-4a1a-b3ac-09a30979b733 | 1 | test | | fa7abc8e-2070-40b6-af84-6a8d78676b89 | 2 | new_rule | | dd70a968-778c-4e45-9044-599effd243a6 | 3 | new_rule_test | +--------------------------------------+--------+----------------+ And I need to output in dict something like this { 1: { "name": "test", "id": UUID(412dacb1-6451-4a1a-b3ac-09a30979b733) }, 2: { "name": "new_rule", "id": UUID(fa7abc8e-2070-40b6-af84-6a8d78676b89) }, 3: { "name": "new_rule_test", "id": UUID(dd70a968-778c-4e45-9044-599effd243a6) } } In the above output, the key is ref_id and the value is again a dict having name and id. I have tried with annotate but it is not working. Only the below code which is working but I need more optimised as the data is very massive. res_dict = Test.objects.filter(publisher_state='Published').values('ref_id', 'name', 'id') final_dict = {row['ref_id']: {'name': row['name'], 'id':row['id']} for row in res_dict} -
I ran makemigrations and migrate but my columns are not reflecting in postgressql database
I'm new to Django, my version is 4.1. I had issues changing the field type of the id column in PostgresSql pgadmin4. But I overrode the ID by making migrations with id in midel.uuidfield like so: from django.db import models from django.contrib.auth.models import AbstractBaseUser import uuid class Profile(AbstractBaseUser): # id = None id = models.UUIDField(unique=True, editable=False, primary_key=True, verbose_name='ID') password = None This worked at last when I ran makegrations and changed the id from None to models.uuidfield before migrating. Now this column and every other column added is not reflecting in the database, that is the PgAdmin4. I tried to troubleshoot by adding a new column, created_time, like so: from django.db import models from django.contrib.auth.models import AbstractBaseUser import uuid class Profile(AbstractBaseUser): # id = None id = models.UUIDField(unique=True, editable=False, primary_key=True, verbose_name='ID') password = None created_time = models.DateTimeField(auto_now_add=True) Now after running makemigrations and migrate, the only record that got added to the database was the created_time. So i checked the migrations folder and in my 0001_initial.py file, it looks like this: # Generated by Django 4.1.7 on 2023-04-04 07:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('last_login', models.DateTimeField(blank=True, … -
stream multi videos using flask_socketio from Multi Clients to one server
can any one plz help me, to write a simple code in python based on Flask and flask_socketio, to recieve and process videos from multi clients in the same time. i used Threads but it's so difficult to apply it on flask_socketio. this is my old code based on socket library but i want to change it to flask_socketio: # Welcome to PyShine # In this video server is receiving video from clients. # Lets import the libraries import socket, cv2, pickle, struct import imutils import threading import pyshine as ps # pip install pyshine import cv2 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print('HOST IP:',host_ip) port = 9999 socket_address = (host_ip,port) server_socket.bind(socket_address) server_socket.listen() print("Listening at",socket_address) def show_client(addr,client_socket): try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: # if a client socket exists data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) # 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) text = f"CLIENT: {addr}" frame = ps.putBText(frame,text,10,10,vspace=10,hspace=1,font_scale=0.7, background_RGB=(255,0,0),text_RGB=(255,250,250)) cv2.imshow(f"FROM {addr}",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break client_socket.close() … -
How to generate jasper report in django using pyreportjasper library with mongodb native connection only?
Previously, I was using pyreportjasper==1.0.2 to generate jasper reports in my django application with mysql database. Now, I using the mongodb for data storage. I want to know how to configure jasper with mongodb native database connection to generate a jasper report. from pyreportjasper import JasperPy import pymongo mongo = pymongo.MongoClient('mongodb+srv://<user>:<password>@<cluster>/?retryWrites=true&w=majority') db = mongo['students']` `jasper = JasperPy() db_connection = { 'driver': 'none', 'database': 'students', 'collection': 'students', 'username': <user>, 'password': <password>, 'host': <cluster>, 'port': <port> } jasper.process( input_file, output_file = output, format_list=format_list, parameters=params, db_connection=db_connection )` I'm getting the following error Caused by: net.sf.jasperreports.engine.JRRuntimeException: No query executer factory registered for the "MongoDbQuery" language. -
Designing a relational data model for a cupboard of infinite depth
I'm trying to implement a relational data model for a cupboard with infinite depth. This means that: The cupboard can have a number shelves Each shelf can have a number of e.g. boxes Each box can have a number of e.g. drawers Etc. The name of each level of depth ('shelf', 'box', ...) can be customized, and the depth of the cupboard is theoretically infinite. I need to store items in the cupboard (e.g. I want to store socks in one of the drawers). Some items take up more space; one item can for instance be stored in a box, occupying all its drawers. Currently, my data model looks like this: Cupboard, with as one of its properties its configuration as a nested dict. For the example above, that's {'name': 'shelf', 'amount': 5, 'child': {'name': 'box', 'amount': 4, 'child': {'name': 'drawer','amount': 3, 'child': None} } } CupboardSpace which has the following properties: a foreign key to the Cupboard location, stored as JSON (eg {'shelf': 1, 'drawer': 2, 'box': 3}) When a new Cupboard is created, my application creates its CupboardSpaces. Item with (amongst others) a foreign key to the cupboard space(s) it occupies. What I want to be able to …