Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weasyprint (Django) save to file or model and not use
is it possible to save the pdf file directly to model without rendering? I just want to database the PDF. I am using Weasyprint although i imagine it would be same for other services like DocRaptor. first just create the pdf. simple. context = {} template = get_template(template_path) html = template.render(context) # Generate the PDF pdf_file = HTML(string=html).write_pdf('test.pdf) then this model. class Reports(models.Model): name = models.CharField() report = models.FileField(upload_to='reports/', null=True, blank=True) and then to save. _pdf = Reports.objects.create( name = 'test', report = pdf_file, ) the name is added put nothing for the pdf. I have a feeling their is some sort of File(BytesIO(pdf_file))) required??? I was able to add the pdf by using this after the save: _pdf.report.save(f'{uuid}.pdf', File(BytesIO(pdf_file))) Why cant I include in the Reports.objects.create? Also when i use this approach the media/reports/pdf will not get deleted when the record gets deleted? is that normal? Thank you -
Django import export to xlsx/csv with custom format for nested Json field
I have the following structures: models.py: class PublicPerson(models.Model): class Meta: verbose_name = "Public Person" verbose_name_plural = "Public People" user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="public_profile", null=True) name = models.CharField(max_length=100) image = models.ImageField(upload_to='public_persons/images', null=True) date_of_birth = models.DateField(null=True, blank=True) bio = models.TextField(max_length=10000, blank=True, null=True) short_description = models.CharField(max_length=200, blank=True, null=True) meta_fields = models.JSONField(default=dict, blank=True, null=True) admin.py from import_export.admin import ImportExportModelAdmin from import_export import resources, widgets, fields as f class PublicPersonResource(resources.ModelResource): meta_fields = f.Field(attribute='meta_fields', column_name='meta_fields') def dehydrate_meta_fields(self, public_person): meta_fields = getattr(public_person, 'meta_fields', None) if meta_fields: return meta_fields return {} class PublicPersonAdmin(ImportExportModelAdmin): ... resource_class = PublicPersonResource ... I am usning django-import-export, and trying to get a more user-friendly import/export capability for the JsonField. More specifically, I have some nested Json data, which I would like to be able to import from / export to an excel (and/or csv if possible) file with a very specific format. So far, I have been able to modify only the export to Json by defining the 'dehydrate_meta_fields' method. I am not sure how to approach the other cases. Thus, export to and import from json seems to work just fine with nested data The level of nesting is not expected to change. It will always be a string : string … -
History in the django administrator
I want to disable the record, record and continue editing buttons but allow me to enter the history and view the changes made. Since if I use the has_change_permission method it returns a 403 error when trying to enter the history. What suggestions could you offer me? I tried the has_change_permission method and hoped it would work -
Django-Ajax "Uncaught ReferenceError: FOO is not defined"
I am new to AJAX. A want to make a call to a django view to update item quantity and change number on the page. I have a template ... {% for item in items %} <div id="quantity">{{ item.quantity }}</div> <button onclick="updateQuantity('{% url "invent:quote-increase-item-ajax" %}')">+</button> ... <script> function docReady(fn) { if (document.readyState === "complete" || document.readyState === "interactive") { setTimeout(fn, 1); } else { document.addEventListener("DOMContentLoaded", fn); }; }; docReady(function() { function updateQuantity(url) { fetch(url, { method: "GET", headers: { "X-Requested-With": "XMLHttpRequest", } }) .then(response => response.json()) .then(data => { document.getElementById("quantity").innerHTML = data; }); } }); </script> And a view: def increase_quote_item_ajax(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': item = QuoteItem.objects.get(id=pk) item.quantity += 1 item.save(update_fields=['quantity']) return JsonResponse({'data': item.quantity}) return JsonResponse({'status': 'Invalid request'}, status=400) else: return HttpResponseBadRequest('Invalid request') But when I click on + button I get Uncaught ReferenceError: updateQuantity is not defined Why isn't my function registering? -
Problem with user permissions and groups in Django
I am trying try to migrate the changes in my model but I get this errors: The field main.CustomUser.groups was declared with a lazy reference to 'custom_auth.group', but app 'custom_auth' isn't installed. The field main.CustomUser.user_permissions was declared with a lazy reference to 'custom_auth.permission', but app 'custom_auth' isn't installed. The field main.CustomUser_groups.group was declared with a lazy reference to 'custom_auth.group', but app 'custom_auth' isn't installed. The field main.CustomUser_user_permissions.permission was declared with a lazy reference to 'custom_auth.permission', but app 'custom_auth' isn't installed. I have custom user model and use custom user creation, registration view instead of Django's basic models and views models.py class CustomUser(AbstractUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=127, unique=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(blank=True, null=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username, email'] objects = CustomUserManager() def get_full_name(self): return self.username def get_short_nane(self): return self.username or self.email.split("@")[0] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' managers.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Users must have an email address')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') … -
Start tutorial after clicked a button that changes view (intro.js)
I have a side bar that is displayed in all views. In that side bar I have a dropdown menu to select some tours that are made with intro.js. There is a quick start, that works perfect. I want to add some options with the names of the views in the tutorial dropdown so that when I click on it I go to the view and start the tutorial. Important, there is an option to start a tutorial when you enter that view, but I don't want that, because if I access redirected from another part it will always start the tutorial, I want it to start only from the tutorial dropdown menu. The problem I have is that my js function switches me to another view but the tutorial starts and stops from one (it shows a fraction of a second). This is what i have. The dropdown menu: <div class="language-selector"> <!-- Dropdown Trigger --> <a id="tutorial" class="dropdown-trigger sidebar-links a" href="#" data-target="tutorialDropdown"> <span style="display: flex; align-items: center;"> <i class="fas fa-question-circle"></i> {% trans "Tutorial" %} <i class="fas fa-caret-down"></i> </span> </a> <!-- Dropdown Structure --> <ul id="tutorialDropdown" class="dropdown-content"> <li> <button class="start-tour-button" onclick="startTourAndRedirect('quick-start', '')"> Quick Start </button> </li> <li> <button class="start-tour-button" onclick="startTourAndRedirect('review-panel', … -
The settings for connecting mysql database in django settings
"django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'lkocalhost'")" When trying to manage.py runserver, The error above keeps popping up that access denied for me to connect mysql to my django project. functionality of local host -
Problems trying to update a record wi a imagefield base64 with django rest framework using drf_extra_fields Base64ImageField
I'm trying to correct a django rest framework api that must save an imagefield with base64 character set image file. I'm doing something wrong but not sure what it is, here my code in details. In settings BASE_DIR = Path(file).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' In my models.py firma_pax = models.ImageField(blank=True, upload_to='img') My database is an Oracle Database, CLOB datatype for column firma_pax -- In my serializers.py from drf_extra_fields.fields import Base64ImageField from .models import Scresolipaxservi class ScreSoliPaxServiFirmSerializer(serializers.ModelSerializer): firma_pax = Base64ImageField(max_length=4000, required=False) class Meta: model = Scresolipaxservi fields = ['firma_pax'] def update(self, instance, validated_data): instance.firma_pax = validated_data.get('firma_pax', instance.firma_pax) return Scresolipaxservi.objects.filter(pk=instance.id).update(firma_pax=instance.firma_pax.url) In my Api View from rest_framework.decorators import api_view from clientes.serializers import ScReSoliPaxServiSerializer, ScreSoliPaxServiFirmSerializer from .models import Scresolipaxservi @api_view(['GET','PUT']) def ReservaPax(request,pk=None): #Consulta de la reserva reserva = Scresolipaxservi.objects.get(id=pk) **# Validate if exits** if reserva: ** #Query: ** if request.method == 'GET': reserva_serializer = ScReSoliPaxServiSerializer(reserva) return Response(reserva_serializer.data, status=status.HTTP_200_OK) **#Update: Image ** if request.method == 'PUT': reserva_serializer = ScreSoliPaxServiFirmSerializer(reserva, data=request.data) if reserva_serializer.is_valid(): reserva_serializer.save() return Response(status=status.HTTP_200_OK) return Response(reserva_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'message':'Reserva No Existe'}, status=status.HTTP_400_BAD_REQUEST) This api work fine with the EndPoint that Query the record with GET method, but the update just set a value like "/media/7e94085e-b6f5-4e51-9bfd-ee18ff803bc1.jpg" to the 'firma_pax' field and not … -
Django-Python: You must set settings.ALLOWED_HOSTS if DEBUG is False
I am trying to deploy a Django-Python based web application in Kubernetes. I'm also trying to setup OpenTelemetry so that I could capture the application metrics and visualise it using prometheus and Grafana. However, when I try to instrument the application data to the OpenTelemetry collector, I am getting the below error: Defaulted container "trojanwall-django" out of: trojanwall-django, opentelemetry-auto-instrumentation-python (init). CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. The first line is specifying the name of the Kubernetes pod which is trojanwall-django and also saying that OpenTelemetry auto-instrumentation has started. Besides that, the below command says something about the ALLOWED_HOSTS in the settings.py file. I tried to add ALLOWED_HOSTS = ["*"] and also ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'otel-collector.otel.svc.cluster.local', '0.0.0.0'] where otel-collector.otel.svc.cluster.local is the host name of the OpenTelemetry collector. I tried to set DEBUG = False, yet still the resulting log is the same. Is this a host blocking issue in the settings.py file? Does anyone know how to fix this? -
Django create connected objects simultaneously
I'm new to Django and wanted to ask how can I solve a problem that I have class InventoryId(models.Model): inventory_id = models.AutoField(primary_key=True) class Laptop(models.Model): name = models.CharField(max_length=30) inventory_id = models.ForeignKey(InventoryId, on_delete=models.CASCADE) class Desktop(models.Model): name = models.CharField(max_length=30) inventory_id = models.ForeignKey(InventoryId, on_delete=models.CASCADE) In the example above I would like models Laptop and Desktop to use inventory_id's that are stored in the same table and are incremental to avoid collisions. example: laptop1 --> inventory_id = 1 desktop1 --> inventory_id = 2 laptop2 --> inventory_id = 3 what's the correct way of doing that in django? I found something that recommends using signals to do that. but i was discouraged by documentation that it may be not the best idea -
Djano webapplication
All of a sudden my login via Microsoft AD (Active Directory) is broken. Post logging in, redirect to http://localhost:8000/auth/redirect?code=0.xxx# 1 gives AuthSecurityError at /auth/redirect Failed to match request state with session state Request Method: GET Request URL: http://localhost:8000/auth/redirect?code=0.xxxm&state=xxxx-xxxx-xxxx-xxxx-xxxx&session_state=xxxx-xxxx-xxxx-xxxx-xxxx Django Version: 4.2.5 Exception Type: AuthSecurityError Exception Value: Failed to match request state with session state Exception Location: D:\workspace\django\projectX\env\lib\site-packages\ms_identity_web_init_.py, line 259, in _verify_state Raised during: ms_identity_web.django.msal_views_and_urls.aad_redirect Python Executable: D:\workspace\django\projectX\env\Scripts\python.exe Python Version: 3.10.10 Can someone help me to identify this issue. earlier it was worming fine in production but suddenly giving this error. -
Django Datatables with HTMX Refresh Causes to Lose Functionality
I'm using Django with bootstrap datatables to display my data. I have it mostly working, but it seems that when I do a call back refresh with HTMX, all of the buttons break. I think what is happening is that a new table is being overlaid on top as the buttons still technically work, but it refers to the old data. Raw table Working filter Filter breaking after refresh As you can see, the table looks slightly different and the search status at the bottom says "showing 1 to 1 of 1 entries). So it works, but isn't updating the div anymore to only show applicable results like it used to. This is how i'm refreshing the table <table class='table table-bordered' id="alert-table" hx-get="{% url 'alert_list' %}" hx-trigger="every 15s" hx-swap="innerHTML"> JS of the datatable: <script> $(document).ready(function () { var table = $("#alert-table").DataTable({ autoWidth: true, lengthChange: true, searching: true, ordering: false, columnDefs: [ { targets: 3, render: function ( data, type, row ) { } } ], dom: 'lBrtip', buttons: [ { // COPY extend: 'copy', text: '<i class="bi bi-files"></i>', className: 'btn btn-secondary', titleAttr: 'Copy' }, { // EXCEL extend: 'excel', text: '<i class="bi bi-file-earmark-spreadsheet"></i>', className: 'btn btn-secondary', titleAttr: 'Excel' } ] … -
AWS ECS Fargate - django runserver will be billed 24/7?
I have a django app in a dockerfile, and I deployed it with ECS Fargate. It works well, but I'm am not sure about how pricing works. python manage.py runserver has to be running all the time because it needs to be listening the incoming requests. Does it mean that my fargate is beign used 24/7. and subsequently billed 24/7?. If that is true, what is the correct way to use a monolithic app in a fargate container minimizing costs? Dockerfile FROM python:3.11-alpine RUN mkdir /app WORKDIR /app COPY . . RUN sed -i 's/\r$//g' ./local/entrypoint.sh RUN chmod +x ./local/entrypoint.sh RUN pip install -r ./local/requirements.txt EXPOSE 8000 ENTRYPOINT ["/bin/sh", "./local/entrypoint.sh"] entrypoint.sh #!/bin/sh set -o errexit set -o pipefail set -o nounset echo "------- RUNNING DJANGO COMMANDS -------" python /app/manage.py makemigrations python /app/manage.py migrate python /app/manage.py runserver 0.0.0.0:8000 -
WhatsApp FLows - Could not decrypt the response received from the server
I'm trying to generate the response for the WhatsApp flow using the WhatsApp bussines api with the following code ` def post(self, request, *args, **kwargs): try: dict_data = json.loads(request.body.decode('utf-8')) encrypted_flow_data_b64 = dict_data['encrypted_flow_data'] encrypted_aes_key_b64 = dict_data['encrypted_aes_key'] initial_vector_b64 = dict_data['initial_vector'] flipped_iv = self.flip_iv(initial_vector_b64.encode('utf-8')) encrypted_aes_key = b64decode(encrypted_aes_key_b64) key_private = open('*******.pem', 'rb').read().decode('utf-8') private_key = load_pem_private_key(key_private.encode('utf-8'), password="*************".encode('utf-8')) aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) aes_key_b64 = b64encode(aes_key).decode('utf-8') flow_data = b64decode(encrypted_flow_data_b64) key = b64decode(aes_key_b64) iv = b64decode(initial_vector_b64) encrypted_flow_data_body = flow_data[:-16] encrypted_flow_data_tag = flow_data[-16:] cipher = Cipher(algorithms.AES(key), modes.GCM(iv,encrypted_flow_data_tag)) decryptor = cipher.decryptor() decrypted_data = decryptor.update(encrypted_flow_data_body) + decryptor.finalize() flow_data_request_raw = decrypted_data.decode("utf-8") hello_world_text = "HELLO WORLD" response_data = { "version": "3.0", "screen": "MY_FIRST_SCREEN", "data": { "hello_world_text": hello_world_text } } response_json = json.dumps(response_data) # Obtendo a chave AES após descriptografar encrypted_aes_key fb_aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # Usando a chave AES para criptografar a resposta response_cipher = Cipher(algorithms.AES(fb_aes_key), modes.GCM(iv)) encryptor = response_cipher.encryptor() encrypted_response = ( encryptor.update(response_json.encode("utf-8")) + encryptor.finalize() + encryptor.tag ) encrypted_response_b64 = b64encode(encrypted_response).decode("utf-8") # Construct the final response final_response = { "encrypted_flow_data": encrypted_response_b64, "encrypted_aes_key": encrypted_aes_key_b64, "initial_vector": initial_vector_b64 } return JsonResponse(final_response, status=200) except Exception as e: print(e) return HttpResponse(status=500, content='ok') def flip_iv(self, iv): flipped_bytes = [] for byte in iv: flipped_byte = byte ^ 0xFF flipped_bytes.append(flipped_byte) return bytes(flipped_bytes) ` The entire … -
Problem deploying Dockerised Django app in Heroku and Fly
I've successfully deployed my Django app with Fly.io. But ever since I followed William Vincent's 'Django for Professionals' by trying to Dockerise my project, I have had no luck with updating my production server. In fact, I cannot deploy at all anymore. I ran heroku logs --tail and this is what I got. May you please offer any explanation as to why my 'release command' is failing? heroku logs --tail » Warning: heroku update available from 7.53.0 to 8.6.0. 2023-10-23T12:37:29.030037+00:00 app[api]: Initial release by user 2023-10-23T12:37:29.030037+00:00 app[api]: Release v1 created by user 2023-10-23T12:37:29.160630+00:00 app[api]: Enable Logplex by user 2023-10-23T12:37:29.160630+00:00 app[api]: Release v2 created by user 2023-10-23T12:39:34.797658+00:00 app[api]: Stack changed from heroku-22 to container by user 2023-10-23T12:39:34.813238+00:00 app[api]: Upgrade stack to container by user 2023-10-23T12:39:34.813238+00:00 app[api]: Release v3 created by user 2023-10-23T12:49:12.780220+00:00 app[api]: Attach DATABASE (@ref:postgresql-clean-38410) by user 2023-10-23T12:49:12.780220+00:00 app[api]: Running release v4 commands by user 2023-10-23T12:49:12.794484+00:00 app[api]: Release v5 created by user 2023-10-23T12:49:12.794484+00:00 app[api]: @ref:postgresql-clean-38410 completed provisioning, setting DATABASE_URL. by user 2023-10-23T12:53:19.000000+00:00 app[api]: Build started by user 2023-10-23T12:54:06.000000+00:00 app[api]: Build succeeded 2023-10-23T12:54:06.158579+00:00 app[api]: Deploy e59a06da by user 2023-10-23T12:54:06.158579+00:00 app[api]: Running release v6 commands by user 2023-10-23T12:54:06.997250+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry … -
Django sessions for anonymous users get deleted when logging in: how to handle shop baskets?
I'm building a webshop where we want anonymous users to also be able to add things to their basket. I thought I'd be smart and created a Basket model like this: class Basket(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) session = models.ForeignKey(Session, blank=True, null=True, on_delete=models.CASCADE) So for logged in users I'd assign the owner field, and for anonymous users I'd assign the session field. Then when the session expires the basket would also be cleaned up, so I wouldn't end up with a ton of database records for baskets that can never be checked out anymore. So far so good. When an anonymous user logs in, I want to assign the basket to that user. And this is where the complications start to add up because when a user logs in they get a new session key, which is not accessible in the request. While I could create some kind of middleware that keeps track of the previous session key, the biggest problem is that by the time user_logged_in signal is called, the session record has already been deleted from the database and thus my basket has also been deleted. I could do a few things, but none seem very … -
Shipping event created from the dashboard does not call handle_shipping_event (django-oscar)
I'm trying to change the shipping event type from the django oscar admin dashboard and send an email to the customer but it seems like it doesn't call the handle_shipping_event under order/processing.py So far, I created a shipping event type and associated it with a communication event type. Then I inherited order/processing.py and add a send email function, however, it seems the shipping event created from the dashboard doesn't call handle_shipping_event under order/processing.py. I can see the shipping event written to the db. from oscar.apps.order.processing import EventHandler as CoreEventHandler class EventHandler(CoreEventHandler): def handle_shipping_event(self, order, event_type, lines, line_quantities, **kwargs): print('It does not print this') # Example implementation self.validate_shipping_event( order, event_type, lines, line_quantities, **kwargs) # send tracking mail self.send_shipped_email(order) return self.create_shipping_event( order, event_type, lines, line_quantities, **kwargs) django-oscar version: 3.1 Python 3.8.10 Thanks -
Customizing PasswordResetView using Django auth views
Well, I need to create a customized view based on Django's PasswordReset view, but for when the User is already logged in. I originally used PasswordChangeView for this, but it automatically redirect the user to PasswordChangeForm, where the user inputs the older password and the new password and then save it. But, for a matter of security, I was requested to, when the user clicks the link to change their password, it automatically send a Password Reset email to they, showing the 'password_reset_done.html' and sending the password reset password. (Don't know if I'm making myself really clear I'm currently studying and this is my first time using stack overflow. I already a custom_password_change view that uses PasswordResetView. `def custom_password_change(request): if request.method == "POST": user = request.user if user.is_authenticated: # Call the Django built-in view for password reset return PasswordResetView.as_view( template_name='registration/password_change_form.html', email_template_name='registration/password_change_email.html', success_url='/password_change/done/' )(request) return render(request, "registration/password_change_form.html")` But it stills demands user to input their email on the PasswordResetForm and then sends the email. I need it to send the email when the user clicks "change password" instead and returning the 'password_reset_done.html' template. -
Is it possible to add a child page from a form in the frontend in Wagtail CMS?
Is it possible to add a child page from a form in the frontend in Wagtail CMS? The reason for this is that when I use the formbuilder the content added is in the Forms section, but I want the content from the form to be a page on its own as this is primary content in the application I built. I was thinking this is possible with the API, but I would think there would be a better solution? -
Django : is it possible to display multiple edit forms as one consolidated form in django admin?
I have three EDIT forms, an environment has one or multiple machines, then a machine has one or multiple users. Now my question is there a way to display the three EDIT forms in one consolidated form with one save button. I want to display three tabs one for Environment and one for Machines (multiple) and one for Users (Multiple), Similar to this : I have already achieved similar results using custom HTML template, but I'm not satisfied, it would be better if I got it done using Django admin configurations my current solution : <div class="tab-content mt-3" id="pills-tabContent"> <div class="tab-pane fade show active" id="environment" role="tabpanel" aria-labelledby="environment-tab"> <div class="step"> <h2>Environment general information</h2> {% for field in environment_form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> </div> <div class="tab-pane fade" id="machine" role="tabpanel" aria-labelledby="machine-tab"> <div class="step"> <h2>Machines information</h2> {% for machine_form in machine_forms %} <h3>Machine {{ forloop.counter }}</h3> {% for field in machine_form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} {% if … -
Celery worker is not starting for my django project hosted on elastic beanstalk
Good day by co-developers. I have a project working on aws elasticbeanstalk and i want to integerate celery to it but the celery worker is not starting and everything is workking fine in development but when i deploy it to elastic ebeanstalk it wont start the worker. my question is that is there any way to start the celery worker or i am during it wrong. below is my Procfile file where i start it with the error i am getting the coonsoole and the log in the instance. thanks in advance. Procfile web: gunicorn --timeout 90 ayjayproject.wsgi celery_beat: celery -A ayjayproject.celery beat -l INFO celery_worker: celery -A ayjayproject.celery worker -l INFO -P solo Log fiile 2023/10/23 10:35:00.909620 [INFO] Running command /bin/sh -c systemctl show -p PartOf celery_beat.service 2023/10/23 10:35:00.919175 [INFO] Running command /bin/sh -c systemctl is-active celery_beat.service 2023/10/23 10:35:00.927731 [INFO] Running command /bin/sh -c systemctl start celery_beat.service 2023/10/23 10:35:00.958395 [INFO] Registering the proc: celery_worker 2023/10/23 10:35:00.958424 [INFO] Running command /bin/sh -c systemctl show -p PartOf celery_worker.service 2023/10/23 10:35:00.975817 [INFO] Running command /bin/sh -c systemctl daemon-reload 2023/10/23 10:35:01.145963 [INFO] Running command /bin/sh -c systemctl reset-failed 2023/10/23 10:35:01.159697 [INFO] Running command /bin/sh -c systemctl is-enabled eb-app.target 2023/10/23 10:35:01.171728 [INFO] Running command … -
Import iso_date_prefix from django_minio_backend problem
I have this exception when running django dev-server: File "/Users/maxim/PycharmProjects/inventory3/inventory/main/models.py", line 22, in <module> **from django_minio_backend import iso_date_prefix** File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/__init__.py", line 1, in <module> from .apps import * File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/apps.py", line 3, in <module> from .models import MinioBackend, MinioBackendStatic File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/models.py", line 30, in <module> from django.utils.timezone import utc **ImportError: cannot import name 'utc' from 'django.utils.timezone'** It started from updating Python's packages to latest versions... -
DRF serializer for many-to-many through tree
here are my models (simplified): class Template(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) areas = models.ManyToManyField("Area", through="AreasOrder") class Area(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) items = models.ManyToManyField("Item", through="ItemsOrder") class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) further_into_tree= models.ManyToManyField("SomeModel", through="SomeModelOrder") class AreasOrder(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) template = models.ForeignKey(Template, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) class ItemsOrder(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) I want to build serializer for getting template by id with all it depedencies. I'm struggling with putting items into area serializer. Can you help me? Serializers: class TemplateSerializer(serializers.ModelSerializer): areas = AreaSerializer(many=True, source="areasorder_set") class Meta: model = Template fields = ("id", "title", "areas", ) class AreaSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField() order_id = serializers.SerializerMethodField() id = serializers.ReadOnlyField(source="area.id") title = serializers.ReadOnlyField(source="area.title") def get_order_id(self, obj): return obj.id def get_items(self, obj): How to access items assigned to area? return ItemSerializer(many=True, source=obj.area.itemsorder_set) # doesn't work - raises error "'RelatedManager' object is not iterable" class Meta: model = AreasOrder fields = ( "id", "title", "items", "order_id" ) I also tried basing AreaSerializer on model Area: class AreaSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, required=False) class Meta: model = Area fields … -
additional fields in ModelSerializer with override update in django
I have a product model like this: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) category = models.ForeignKey(ProductCategories, on_delete=models.CASCADE) brand = models.ForeignKey(ProductBrand, on_delete=models.SET_NULL, blank=True, null=True) score = models.PositiveIntegerField(blank=True, null=True) insurnace = models.PositiveIntegerField(blank=True, null=True) property = models.ManyToManyField(ProductProperty, blank=True) is_flagship = models.BooleanField(default=False) is_exhibition = models.BooleanField(default=False) seen = models.IntegerField(default=0) for saving images, prices and details i wrote this three model: class ProductImage(models.Model): image = models.ImageField(upload_to='product_image/') product = models.ForeignKey(Product, related_name='image', on_delete=models.SET_NULL, blank=True, null=True) is_main_image = models.BooleanField(default=False) class ProductDetail(models.Model): title = models.ForeignKey(ProductDetailTitle, related_name='value', on_delete=models.CASCADE) value = models.CharField(max_length=500) product = models.ForeignKey(Product, related_name='detail', on_delete=models.CASCADE) class ProductPrice(models.Model): product = models.ForeignKey(Product, related_name='price', on_delete=models.CASCADE) color = models.ForeignKey(ProductColor, on_delete=models.CASCADE) price = models.PositiveIntegerField() quantity = models.PositiveIntegerField() i wrote this serializer for manage product class ProductAdminSerializer(serializers.ModelSerializer): images = serializers.ListSerializer(child=serializers.IntegerField()) prices = ProductPriceForProductAdminSerializer(many=True) properties = serializers.ListSerializer(child=serializers.IntegerField()) details = ProductDetailForProductAdminSerializer(many=True) class Meta: model = Product fields = ['id', 'title', 'category', 'brand', 'images', 'description', 'properties', 'is_flagship', 'is_exhibition', 'prices', 'score', 'insurnace', 'details'] def create(self, validated_data): title = validated_data.get('title') category = validated_data.get('category') brand = validated_data.get('brand') description = validated_data.get('description') is_flagship = validated_data.get('is_flagship') is_exhibition = validated_data.get('is_exhibition') score = validated_data.get('score') insurnace = validated_data.get('insurnace') product = Product.objects.create(title=title, category=category, brand=brand, description=description, is_flagship=is_flagship, is_exhibition=is_exhibition, score=score, insurnace=insurnace) image_ids = validated_data.get('images') ProductImage.objects.filter(id__in=image_ids).update(product=product) properties = validated_data.get('properties') if properties is not None: property_objs = ProductProperty.objects.filter(id__in=properties) product.property.set(property_objs) prices … -
Django JSONB find value less than
I have a sample JSONB dataset below, this is one column entry from a single row: [ { "id": "xxx", "type": "thing", "value": { "date": "2023-10-21" } }, { "id": "xxy", "type": "thing", "value": { "date": "2023-10-19" } } ] I need to find if one of the 'date' values is less than 'some_value' - please see pseudocode below: Q(columnName__{arrayOfItems}__value__date__lt=some_value) I can find if an exact value exists but need the value to be variable, for example the below works: Q(columnName__contains=[{"value": {"date": "2023-10-21"}}]) I think I need to add a subquery for the date itself ("2023-10-21") to see if it is less than some other date but currently unable to do this. Spent a few days so far, any comments welcome to help guide me. Many thanks in advance.