Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
if one user login send message creating one message at a time 2 users login send a message create 2 messages
how to avoid dulpicate message creatinhg 2 users login at a one time class ChatConsumer(WebsocketConsumer): def connect(self): print("here") self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = f"chat_{self.room_name}" query_string = self.scope['query_string'].decode('utf-8') query_params = parse_qs(query_string) if 'user_id' in query_params: user_id = query_params['user_id'][0] print("userid.......................................................................................", user_id) user = self.authenticate_user(user_id) if user.is_authenticated: print("sucess authentication....................") # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def authenticate_user(self, user_id): def sync_authenticate_user(): try: user = User.objects.get(id=user_id) self.scope['user'] = user except User.DoesNotExist: self.scope['user'] = AnonymousUser() thread = threading.Thread(target=sync_authenticate_user) thread.start() thread.join() return self.scope['user'] def receive(self, text_data=None, bytes_data=None): # parse the json data into dictionary object text_data_json = json.loads(text_data) if text_data_json.get('action') == 'get_chat_history': conversation = Conversation.objects.get(id=int(self.room_name)) all_messages = Message.objects.filter( conversation_id=conversation).order_by('timestamp') serializer = MessageSerializer(instance=all_messages, many=True) message_list = serializer.data self.send(text_data=json.dumps({ 'type': 'message_list', 'messages': message_list })) else: chat_type = 'chat_message' return_dict = { 'type': chat_type, 'message': text_data_json.get('message'), 'attachment': text_data_json.get('attachment') } async_to_sync(self.channel_layer.group_send)( self.room_group_name, return_dict ) def chat_message(self, event): print("event.............................................................................................", event) text_data_json = event.copy() text_data_json.pop("type") message = event.get("message", None) attachment = event.get("attachment", None) print(message, attachment, "........................................................................") conversation = Conversation.objects.get(id=int(self.room_name)) sender = self.scope['user'] sender_id = sender.id print("username is...............................................................", sender) print("user is...................", sender_id) print(conversation.id,"converstaionid") sender_id = self.scope['user'].id message = event.get("message", None) attachment = event.get("attachment", None) conversation = Conversation.objects.get(id=int(self.room_name)) if attachment: file_str, … -
checkboxinput overlaid on the label
I am working with a form in django with crispy form and it has many fields, and the checkboxinput field does not render well in the html, it is overlapped in the label and very big. previously i was using another template style but when i changed the html, the checks were broken form.py class TestForm(forms.ModelForm): class Meta: model = Test fields = [ 'test1', 'test2' ] labels = { 'test1':'Test 1', 'test2':'Test 2',} widgets = { 'test1':forms.CheckboxInput(attrs={'class':'form-check-label'}), 'test2':forms.CheckboxInput(attrs={'class':'form-check-label'}), form.html <div class="form-group col-md-4 d-flex align-items-center pt-4 pl-2"> {{ form.test1 | as_crispy_field }} </div> <div class="form-group col-md-4 d-flex align-items-center pt-4 pl-2"> {{ form.test2 | as_crispy_field }} </div> This is how the checkboxes and the labels look -
Why is django ManyToManyField asymmetric?
A classic example of a ManyToManyField (django 4.2 docs or SO) looks something like this: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Why the asymmetry? We have this natural scheme where a Person can belong to Groups through a Membership and vice versa. So why does Person make no reference to this? Or, perhaps better phrased, why does the framework see fit to encourage us to state the relationship only on one side? # No one writes this: class Person(models.Model): name = models.CharField(max_length=128) groups = models.ManyToManyField(Group, through='Membership') -
django, get one child for every parent
the tables i have some items (Monitors, Printers etc). The items may change owner and i keep history of all the owners. i want to get only the most recent owner (owner's change date) for each item, ordered by owner's name. For example: table items item_id brand serial 1 BrandA s22222 2 BrandB s33333 3 BrandC s11111 table owners name is owner's name, date is when the item changes owner. (in the example item 1 had 2 owners and item 2 had 3 owners. owner_id item_id name date 1 2 B 2023-6-22 2 3 D 2023-6-30 4 2 F 2023-6-20 3 1 A 2023-6-25 4 2 E 2023-6-21 5 1 C 2023-6-26 i want the next table as result: owner_id brand serial item_id name date 1 BrandB s33333 2 B 2023-6-22 5 BrandA s22222 1 C 2023-6-26 2 BrandC s11111 3 D 2023-6-30 and i think the sql below gives what i want. Select * From (SELECT *, MAX(date) as last_date FROM owners GROUP BY owner_id) as my_owners INNER JOIN items on owners.owner_id = items.owner_id ORDER BY last_date the problem is i cant find a way to do it with a django queryset (btw i use sqlite3 db) the models.py … -
No Reverse match after using slug
I have been trying to adopt slugs in Django project to give beautiful urls since i have more than one app in the Django project but I have encountered this error. Am stuck and I do not know to sort it out. The following are appname/models.py code class Standard(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(null=True, blank = True) description = models.TextField(max_length=500, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) class Subject (models.Model): subject_id = models.CharField(max_length=100, unique= True) name = models.CharField(max_length=100, unique=True) slug = models.SlugField(null=True, blank=True) standard = models.ForeignKey(Standard,on_delete=models.CASCADE,related_name="subjects") image = models.ImageField(upload_to=save_subject_img, blank=True,verbose_name='Subject Image') description = models.TextField(max_length=500, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.subject_id) return super().save(*args, **kwargs) class Lesson (models.Model): lesson_id = models.CharField(max_length=250, unique=True) standard = models.ForeignKey(Standard, on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name="lessons") name = models.CharField(max_length=250) position = models.PositiveSmallIntegerField(verbose_name="chapter no.") slugs = models.SlugField(null=True, blank=True) class Meta: ordering = ['position'] def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) Then the following is my urls.py file in the app directory app_name = 'appname' urlpatterns = [ path('',views.StandardListView.as_view(),name='standard_list'), path('<slug:slug>', views.SubjectListView.as_view(), name='subject_list'), path ('<str:standard>/<slug:slug>/', views.LessonListView.as_view(),name='lesson_list'), ] Everything was working … -
How to use coalesce function in Django ORM?
I have a sql query whose coalesce portion that looks like below "coalesce(MAX(case when status = 'OK' then 'OK' end),'') as final_status" I am writing the same query in Django ORM. But I am not getting any value for the coalesce portion. This is how the coalesce portion looks like .annotate(final_status=Max(Coalesce( Case( When(status__contains=['OK'], then=Value('OK')), default=Value(''), output_field=CharField() ), Case( When(~Q(notify__contains=['OK']), then=Value('')), default=Value(''), output_field=CharField() ) ))) In regular sql query, I am getting values in final_status column but in django query, the final_status column is empty for all the rows What am I doing wrong? -
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 …