Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django i have problems with HTMX: a dependent combobox doesn't work. The first combobox is populated, the second is empty
I have a country combobox and a trip combobox. Both are employees. They use the same table of a database (i don't want to use two tables with foreignkey). I think I came close to the solution, but something is not working. The first combobox is populated correctly, while the second combobox is empty. For example if I select Spain in Country, in the combobox trip I should see: Madrid-Barcelona, and then Sevilla-Bilbao, because they are in the same database table: ID | COUNTRY | DEPARTURE | DESTINATION | | france | paris | lyon | | france | marseilles| grenoble | | spain | madrid | barcelona | | spain | seville | bilbao | models.py from django.db import models class Trip(models.Model): country = models.CharField(max_length=100) departure = models.CharField(max_length=100) destination = models.CharField(max_length=100) @property def journey(self): return f"{self.departure}-{self.destination}" urls.py from django.urls import path from . import views urlpatterns = [ path('', views.trip_selector, name="trip_selector"), path('', views.trips, name='trips') ] form.html {% extends 'base.html' %} {% block content %} <!-- First Combobox --> <label for="id_country">Country</label> <select name="country" id="id_country" hx-get="{% url 'trips' %}" hx-target="#id_trip" hx-indicator=".htmx-indicator"> {% for country in countries %} <option value="{{ country }}">{{ country }}</option> {% endfor %} </select> <!-- Second Combobox ??????? … -
Django and "OSError: [WinError 87] The parameter is incorrect" when using venv virtual environment
I am building a website in django and using a python venv in my development environment. When I tried to run 'python manage.py runserver' I got the error below. I have used this venv virtual enviroment in my project before without any problems. Does anyone know why I might be getting the error below? If so, does anyone know how I might be able to fix this? As an fyi, I am developing on a windows machine. (.venv) PS C:\Users\username> python manage.py runserver Error in sitecustomize; set PYTHONVERBOSE for traceback: OSError: [WinError 87] The parameter is incorrect: 'C:\\Users\\username\\.venv\\Lib\\site-packages' Traceback (most recent call last): File "C:\Users\username\manage.py", line 22, in <module> main() File "C:\Users\username\manage.py", line 11, in main from django.core.management import execute_from_command_line File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1138, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1078, in _find_spec File "<frozen importlib._bootstrap_external>", line 1504, in find_spec File "<frozen importlib._bootstrap_external>", line 1476, in _get_spec File "<frozen importlib._bootstrap_external>", line 1616, in find_spec File "<frozen importlib._bootstrap_external>", line 1659, in _fill_cache OSError: [WinError 87] The parameter is incorrect: 'C:\\Users\\username\\.venv\\Lib\\site-packages' I've tried searching for help with no success yet unfortunately. -
relation "django_content_type" already exists django
oke, I have a django application. And I tried to update the models. So I did a makemigrations and migrate. But that didn't worked. So I truncated the table django_migrations. And I did a python manage.py makemigrations: Migrations for 'DierenWelzijnAdmin': DierenWelzijnAdmin\migrations\0001_initial.py - Create model Category - Create model Animal but when I try now: python manage.py migrate. I get this errors: Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "C:\repos\DWL_backend\env\lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "django_content_type" already exists But I see that changes have been made in the tables. and the app works fine. But I still get this warning when I do a : python manage.py runserver 192.168.1.135:8000 You have 25 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): accounts, admin, auth, authtoken, contenttypes, sessions. Run 'python manage.py migrate' to apply them. July 24, 2023 - 15:49:58 Django version 4.2.3, using settings 'DierenWelzijn.settings.local' Starting development server at http://192.168.1.135:8000/ Quit the server with CTRL-BREAK. Question: how to resolve this error? -
Django overwriting data in mysql database
Hey I am creating a project in django where I keep track of orders. Now I want to add all the items to an orderline table to keep track of which items are ordered. But when I want to add multiple items from 1 order to the database it only enters the last one. My guess is that it overrides the previous one. This is my Orderline model class in django. class OrderLine(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() size = models.CharField(max_length=50) def __str__(self): return self.to_dict() def to_dict(self): return { 'product': self.product.to_dict(), 'order': self.order.to_dict(), 'quantity': self.quantity, 'size': self.size } def add(self, product, order, quantity, size): self.product = Product.objects.get(id=product) self.order = Order.objects.get(id=order) self.quantity = quantity self.size = size self.save() return self.to_dict() def add_orderline(self, product, order, quantity, size): if self.exists(product, order, size): orderline = OrderLine.objects.get(product=product, order=order, size=size) orderline.quantity += quantity orderline.save() return orderline.to_dict() else: orderline = self.add(product, order, quantity, size) return orderline def exists(self, product, order, size): return OrderLine.objects.filter(product=product, order=order, size=size).exists() def get_all_by_order(self, order): return OrderLine.objects.filter(order=order) This is the code that should create multiple orderlines. for idx in range(len(cart_items)): orderline = order_line.add_orderline(cart_items[idx],uncomplete_order["id"], cart.get_by_user(body['user_id'])[idx]["quantity"], cart.get_by_user(body['user_id'])[idx]["size"]) print(orderline) NOTE: it is not important to know the … -
Django Admin "TrustedHTML" Error with filter_horizontal on localhost
I'm currently working on a Django project and have run into an issue with the Django admin interface. I have a Report model, which is set up as follows: class Report(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, editable=False, related_name="created_reports") analyses = models.ManyToManyField(Analysis, related_name="reports") The corresponding admin class is: @admin.register(Report) class ReportAdmin(admin.ModelAdmin): list_display = ("uuid", "owner", "created", "modified") filter_horizontal = ("analyses",) When I interact with the filter_horizontal widget on my local machine, none of the expected actions (select analysis, select all analyses) work and the console logs an error message that references 'TrustedHTML': SelectBox.js:17 Uncaught TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment. at Object.redisplay (SelectBox.js:17:27) at move (SelectBox.js:76:23) at move_selection (SelectFilter2.js:107:21) at HTMLAnchorElement.<anonymous> (SelectFilter2.js:116:17) Also it should be noted that this behavior works as expected in staging and prod and it is only my local dev environment that is impacted. I am using django version 3.2.20 served using a docker container. I am also using nginx in a docker container with the following config: upstream myapp { server myapp:80; } I'm using nginx:1.25.1-alpine as my nginx docker … -
Django container unable to connect to other container on the same network
I'm very new to docker, now I am trying to run django with mysql in docker through docker-compose, but I always get this error: ping: mysql: Name or service not known I am using Docker version 24.0.4, build 3713ee1 and Docker Compose version v2.17.3 I have read the documentation it says When you run docker compose up, the following happens: A network called myapp_default is created. A container is created using web’s configuration. It joins the network myapp_default under the name web. A container is created using db’s configuration. It joins the network myapp_default under the name db. Here is my docker-compose file that I am using; version: "3.8" services: mysql: image: mysql restart: always env_file: - .env volumes: - db_data:/var/lib/mysql ports: - "3306:3306" backend: container_name: analytics_api build: context: . command: gunicorn analytics_api.wsgi --bind 0.0.0.0:8001 --timeout 120 --workers 4 ports: - "8001:8001" depends_on: - mysql links: - "mysql:database" volumes: db_data: driver: local Also I have checked the network and it has both the containers in there [ { "Name": "radioapis_default", "Id": "7a3a7a38886f7e19bdd6e3642bc9cf0b48fb6376c171a3ccae2cacde00b3f329", "Created": "2023-07-24T12:58:10.131998722Z", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.22.0.0/16", "Gateway": "172.22.0.1" } ] }, "Internal": false, "Attachable": false, … -
how to django chat appilication create in django restapi? [closed]
i want a solution for following question. I must develop a chat application in Django using Rest API. How to develop a django chat application using the django rest api, client-side django, javascript, html, and css, and real-time chat (django-restframework). -
implementing custom backend is not recognized by django
Following the usually smart answer from one of djangos experts I want to implement my own backend, overwriting SQLite3 and Postgres JSON handling method. What I did: created a backends folder in my app directory: put base.py in there from django.db.backends.sqlite3.base import DatabaseWrapper as DBW import json class DatabaseWrapper(DBW): def adapt_json_value(self, value, encoder): return json.dumps(value, ensure_ascii = False, cls = encoder) changed settings.py accordingly (so I thought): DATABASES = { 'default': { 'ENGINE': "Shelf.backends.sqlite3json", 'NAME': BASE_DIR.joinpath("db.sqlite3"), } } This throws the error: django.core.exceptions.ImproperlyConfigured: django.db.backends.sqlite3json' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
django.db.utils.ProgrammingError: column "" of relation "" does not exist
I hava a django application. And I try to update the models. So I already have done: python manage.py makemigrations and python manage.py migrate. But I still get an error. So this is the model: class Animal(models.Model): class UISChoices(models.TextChoices): EMPTY = "", "" A = "A", "A" B = "B", "B" AB = "AB", "A/B" class PetChoices(models.TextChoices): EMPTY = "", "" A = "A", "A" B = "B", "B" C = "C", "C" D = "D", "D" E = "E", "E" F = "F", "F" name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, editable=False) uis = models.CharField(max_length=5, choices=UISChoices.choices, default=UISChoices.EMPTY) pet_list = models.CharField(max_length=2, choices=PetChoices.choices, default=PetChoices.EMPTY) description = models.TextField(max_length=1000, blank=True, null=True) feeding = models.TextField(max_length=1000, blank=True, null=True) housing = models.TextField(max_length=1000, blank=True, null=True) care = models.TextField(max_length=1000, blank=True, null=True) literature = models.TextField(max_length=1000, blank=True, null=True) images = models.ImageField(upload_to="media/photos/animals", blank=True, null=True) category = models.ForeignKey(Category, related_name='animals', on_delete=models.CASCADE) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) def img_preview(self): # new return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') class Meta: verbose_name = "animal" verbose_name_plural = "animals" def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): self.slug = slugify(self.name) super(Animal, self).save() def __str__(self): return self.name serializer: class AnimalSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Animal fields = ['id', 'name', "sc_name", "uis", "pet_list", 'description', "feeding", "housing", "care", "literature", … -
Calculation after POST action with Django
I am trying to create an API for efficiency calculation using Django Rest Framework. After sending and saving the consumption and production values to the database, I want to perform calculations on the data and find the efficiency and save it to database. How should I structure the project? How can I trigger the calculation function? Could you share an example that can help with this? -
Import Django Model Serializer and Use it in Model's Save Method
Peace, I am getting ImportError: cannot import name 'Tenant' from 'tenant_profile.models' I am assuming it's due to circular import. # models.py from .serializers import TenantSerializer class Tenant(models.Model): # model fields def save(self, *args, **kwargs): _ = super().save(*args, **kwargs) data = TenantSerializer(self).data # do something return _ # serializers.py from .models import Tenant class TenantSerializer(serializers.ModelSerializer): class Meta: model = Tenant fields = '__all__' A Pythonic way to fix would be much appreciated. -
I have a file called test.local. How can I redirect dns to my web project written with dijango running on raspberry pi using this file?
How should I use the test.local file I have? How can I do domain forwarding in my application? -
Django many to many field save after commit
Branch Model which to separate to data branch wise class Branch(models.Model): # Branch Master status_type = ( ("a",'Active'), ("d",'Deactive'), ) code = models.CharField(max_length=100, null=True, blank=True, default=None) name = models.CharField(max_length=100, unique=True) suffix = models.CharField(max_length=8, unique=True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.name Vendor Model which is I am use to separate branch wise vendors class Vendor(models.Model): status_type = ( ("a",'Active'), ("d",'Deactive'), ) code = models.CharField(max_length=100, null=True, blank=True, default=None) branch = models.ManyToManyField(Branch) company = models.CharField(max_length=200) name = models.CharField(max_length=200) phone = models.CharField(max_length=11, unique = True) email = models.EmailField(max_length=254, unique = True) gst = models.CharField(max_length=15, unique = True) pan_no = models.CharField(max_length=10, unique = True) add_1 = models.CharField(max_length=50, null=True, blank = True) add_2 = models.CharField(max_length=50, null=True, blank = True) add_3 = models.CharField(max_length=50, null=True, blank = True) city = models.CharField(max_length=50, default=None) state = models.CharField(max_length=50, default=None) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') **this is forms.py file ** class VendorForm(ModelForm): class Meta: model = Vendor fields = '__all__' labels = { 'add_1':'Address', 'add_2':'Address', 'add_3':'Address', } exclude = ['created_by', … -
Celery, Django, Eventlet, django-celery-beat "raise NotImplementedError("unsupported platform")"
Celery, Eventlet, django-celery-beat for a project, but when give the bellow command celery -A app worker -P eventlet -c 100 -l info --logfile=celery.log I get the following error (sample_app) neerajgoyal@Neerajs-MacBook-Pro app % celery -A app worker -P eventlet -c 100 -l info --logfile=celery.log Traceback (most recent call last): File "/Users/neerajgoyal/miniconda3/envs/sample_app/bin/celery", line 10, in <module> sys.exit(main()) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/celery/__main__.py", line 13, in main maybe_patch_concurrency() File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/celery/__init__.py", line 140, in maybe_patch_concurrency patcher() File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/celery/__init__.py", line 101, in _patch_eventlet import eventlet.debug File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/__init__.py", line 17, in <module> from eventlet import convenience File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/convenience.py", line 7, in <module> from eventlet.green import socket File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/green/socket.py", line 21, in <module> from eventlet.support import greendns File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/support/greendns.py", line 79, in <module> setattr(dns, pkg, import_patched('dns.' + pkg)) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/support/greendns.py", line 61, in import_patched return patcher.import_patched(module_name, **modules) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/patcher.py", line 132, in import_patched return inject( File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/patcher.py", line 109, in inject module = __import__(module_name, {}, {}, module_name.split('.')[:-1]) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/dns/asyncquery.py", line 38, in <module> from dns.query import ( File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/dns/query.py", line 63, in <module> import httpcore File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/__init__.py", line 1, in <module> from ._api import request, stream File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/_api.py", line 5, in <module> from ._sync.connection_pool import ConnectionPool File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/_sync/__init__.py", line 1, in <module> from .connection import HTTPConnection File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/_sync/connection.py", line 12, … -
Django filter on many to many with having count
After a lot of try, I am not able to translate this kind of sql queries into django filtering. Basically, it is retrieving all users with at least x selected tags (and other filters). In the case of two tags, users need to have both tags, I don't want to retrieve users with at least one of the tag. Here are my definitions: class User(models.Model): name = models.CharField(max_length=64) tags = models.ManyToManyField(Tag) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Tag(models.Model): name = models.CharField(max_length=128) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) SQL query will look like: SELECT user.id FROM user INNER JOIN "user_tags" ON ("user"."id" = "user_tags"."user_id") AND "user_tags"."tag_id" in (8, 163) group by "user"."id", user_tags.user_id having count(*) = 2 ORDER BY user.id DESC LIMIT 100; As you can see, the having count(*) part is done on the created m2m table user_tags, and the filtering of tags also "user_tags"."tag_id" in (8, 163) Is it achievable in a django way? All my attempts use user and tab tables, never the created table. Thanks, -
Celery retrieve exception type or info from previous retries
My purpose is to set different max_retries for each exception type Example code @app.task(bind=True, serializer='json') def create_user(self, client): try: data = client.get('users/') except requests.ConnectionError as e: raise self.retry(exc=e, max_retries=10) from e except requests.ReadTimeout as e: raise self.retry(exc=e, max_retries=5) from e The goal is to stop retrying task only if 5 ReadTimeout errors occured or 10 ConnectionError occured. The current code unifies the retries: if 6 ConnectionErrors occured, and then ReadTimeout is raised the celery does not retry the task. Is there a way to set retries for each error type -
How to add calculated field to Django model
I am building a database system and am trying to add calculated field to model as well as the template. I want to field to automatically generate the result of to the values entered on two fields. I am building a database system and am trying to add calculated field to model as well as the template. I want to field to automatically generate the result of to the values entered on two fields. This is my model.py: class VinanPet(models.Model): transaction_Date = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True, null=True) entry_Date = models.DateTimeField(null=True) branch = models.CharField(max_length=300, null=True) product = models.CharField(max_length=300, null=True) tank_Opening = models.DecimalField(max_digits=13, decimal_places=3, null=True) tank_Closing = models.DecimalField(max_digits=13, decimal_places=3, null=True) tank_Difference = models.DecimalField(max_digits=13, decimal_places=3, null=True) pump_Opening = models.FloatField(null=True) pump_Closing = models.FloatField(null=True) pump_Difference = models.DecimalField(max_digits=13, decimal_places=3, null=True) price = models.DecimalField(max_digits=13, decimal_places=3, null=True) amount = models.DecimalField(max_digits=13, decimal_places=3, null=True) expenses = models.DecimalField(max_digits=13, decimal_places=3, null=True) bank = models.DecimalField(max_digits=13, decimal_places=3, null=True) teller_id = models.IntegerField(null=True) teller = models.ImageField(upload_to="teller", null=True) And this is my forms.py from django import forms import calculation from django.forms.widgets import NumberInput from .models import VinanPet class ManagerForm(forms.ModelForm): class Meta: model = VinanPet fields = "__all__" widget = { 'entry_Date': forms.DateInput(attrs={'type': 'date'}), 'tank_Difference': forms.DecimalField(disabled=True,widget=calculation.FormulaInput('tank_Opening-tank_Closing')) } The calculated field only work on form not on database. -
How to list the field names from a Django serializer
I have a model serializer and I was wondering how to get a list of the names of the fields of this serializer. Similarly, I know how to get a list of the fields form a model and from a form. Example model: class Account(models.Model): account_holder = models.CharField(blank=False, max_length=50) age = models.IntegerField(blank=False) salary = models.DecimalField(blank=False, max_digits=10, decimal_places=2) Then the list of fields can be derived from: obj_fields = Account._meta.get_fields() # as objects [field.name for field in Account._meta.get_fields()] # as list of strings # output: ['id', 'account_holder', 'age', 'salary'] From the form: class AccountForm(forms.ModelForm): class Meta: fields = '__all__' model = Account The list of the form fields (one of the possible methods without derailing into a different topic): fields = AccountForm.base_fields # as dictionary of objects [field for field in AccountForm.base_fields.keys()] # as list of strings # output: ['account_holder', 'age', 'salary'] And I have a serializer: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ( 'id', 'account_holder', 'age', 'salary', 'age_score', 'salary_score', ) which has a few more fields than the model. But for example using the following, it throws an error: >>> AccountSerializer.get_field_names() Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: ModelSerializer.get_field_names() missing 3 required … -
Building a WhatsApp Chat Bot with Django & MySQL for Collecting User Information [closed]
I am working on a project to build a WhatsApp chat bot using Django as the backend framework. The primary goal of the bot is to interact with users on WhatsApp and collect their information, such as name and email. However, the information criteria can vary, including long paragraphs or options like "Yes" or "No." My requirements are as follows: WhatsApp Integration: I need to integrate the chat bot with WhatsApp so that users can interact with it directly through the messaging app. User Information Collection: The chat bot should be able to prompt users for their information, and the responses could be simple data like name and email or more complex like paragraphs and options. Django Backend: I plan to use Django as the backend framework for processing and storing the collected user information in a MySQL database. MySQL Database: The user information should be stored in a MySQL database for further analysis and usage. I'm not sure how to connect these different components effectively. If you have prior experience building similar chat bots or integrating WhatsApp with Django, I would greatly appreciate your guidance on the best practices and tools to achieve this. Additionally, I'm open to using … -
I want to customize my password field in django admin panel to implement hide/unhide functionality
I want to customize my password field in django admin panel to implement hide/unhide functionality. #app/models.py from django.db import models class CustomInput(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=128) I want to add a "eye" sign in password field and implement hide/unhide functionality inside my admin panel. Please refer image for admin panel reference -
Make a regular expression in the search in VS code
I'd like to change the imghtml tag to django html with {%static Can you make a regular expression in the ctrl + f function so I can change it at once? ex) <img src="../img/logo.png" => <img src=" {%static 'img/logo.png' %}" r'<img\s+src="(.*?)"' But I can't find a way to change the code while preserving the middle values -
Stop the currently running task by celery worker in Django
I have a Django application and React as my frontend framework and I am using celery for running lengthy tasks which do take a lot of time and everything is working fine. Also I am providing real time status of the each task running on the celery via celery signals and all . Also I have created a database table which stores the status of all the tasks that are running , like when the task is created , i create a row with the parameters and they are unique so that task with same parameters won't run if its already running or is in the queue , so the user interface is good . But there are few tasks which need to stop and also the user have the authority and permission to stop the tasks that are running as i am updating every user for the tasks. Now if the task is in the queue i can use revoke to stop the from being executed . from celery.task.control import revoke revoke(task_id, terminate=True) But the thing is that , i have tasks which are very lengthy , so the user may want to stop the task and focus on … -
Internal Server Error for a football match prediction app
I am developing a football match prediction app in python/django. views.py has 3 major functions: def (matrix) generates random numbers using "secrets" module of python. The numbers are validated with an algorithm which returns either "valid" or "invalid". If valid, the next function is called, otherwise, new set of random numbers are generated. def (sincerity) checks whether the match is actually scheduled. An algorithm returns either "sincere" or "Oops! We detected an error ..." If sincere, the next function is called, otherwise, user gets a response in frontend "Oops! We detected an error ..." def determine_winner(home_team, away_team) uses 5 algorithms tagged formula 1, formula 2, ... formula 5. A summary of the 5 formulae returns "home team will win", "away team will win", "it will be a draw" or "sorry, we cannot determine match winner". These steps make up the function, def process_form (request). When I submit request, instead of getting the desired response, I get "Internal Server Error: /process_form/". Note that app is yet to be deployed to a live server. Internal Server Error: /process_form/ Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, … -
make manytomany field hyperlink
thanks for your time i need to change categories in api my category and books models are manytomany my serializer: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class BookSerializer(serializers.ModelSerializer): price_after_discount = serializers.SerializerMethodField() def get_price_after_discount(self, instance): discounts = instance.get_discount(user=self.context['request'].user) def formatNumber(num): if num % 1 == 0: return int(num) else: return "{:.1f}".format(num) return formatNumber(float(instance.price)*((discounts)/ 100 )) class Meta: model = Book fields = ('id','isbn','title','content','price','authors','categories','price_after_discount') result : { "id": 1, "isbn": "978-1-4061-9242-1", "title": "Energy carry different lot. Back room practice with.", "content": "Suddenly various answer author.", "price": "7346.00", "authors": [ 1, 2 ], "categories": [ 2 ] }, but i need: "categories": [ "http://127.0.0.1:8000/category/2/" ], thanks for reading. -
How to upload a file in a nested directory to Storage accounts File Share service using Python SDK?
I am trying to upload a file to the path, using ShareDirectoryClient Class of Azure Python SDK.I have attached below the code and errors that I am getting. path = "users/vaibhav11/projects/assets/fbx" directories = path.lower().strip("/").split("/") for directory in directories: try: directory_client = directory_client.get_subdirectory_client(directory) if not directory_client.exists(): directory_client.create_directory() except Exception as e: print(e.args) with directory_client.get_file_client(file_name=upload_file.name) as file_client: file_client.upload_file(data = file_content, length=len(file_content)) print("Uploaded") The "directory_client" is an object of ShareDirectoryClient, which is used in the above code snippet to create directories. The problem faced is, with every directory that is being created I get the below Exception. ('The specifed resource name contains invalid characters.\nRequestId:fc43b173-e01a-000c-1ae8-bd388a000000\nTime:2023-07-24T04:37:52.5072468Z\nErrorCode:InvalidResourceName',) ClientAuthenticationError Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. ErrorCode:AuthenticationFailed authenticationerrordetail:The MAC signature found in the HTTP request 'E0eObuCq+OdHAtf4qG80kb3wprxR4vwIsDpjinnVvUM=' is not the same as any computed signature. Server used following string to sign: 'PUT.......' And sometimes I even get ClientAuthenticationError. I'm not really sure, what is creating the problem in both the cases. Any solutions and suggestions are open. Thanks!