Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset retrieve many-to-many choosen field values
I have a class A(Aid,Aname,manytomanyfield) with a many to many relationship to a class B(Bid,Bname). I have for example three rows in A : Aid,Aname 1,foo 2,bar 3,baz I have for example three rows in B: Bid,Bname 1,foo 2,bar 3,baz With Django ORM I don't really see the relationship class, C which contains for example: Aid,Bid 1,1 1,2 1,3 2,2 2,3 I want all A rows that match for example class B 3,baz rows, in django "A.objects.filter(manytomanyfield=B.get(Bname=baz))": Aid,Aname,Bname 1,foo,baz Is there a way to retrieve all possible values of A relationship with B after filtering? I want: Aid,Aname,Bname,manytomanyfield 1,foo,baz,"foo,bar,baz" In django admin, django produce this result with a new request for every line of the html table. I wonder if we can do this with only one ORM request. Sorry for my english! -
How to upload file, encrypt and make available to download in Django?
This question might be a bit confusing, but I don't know how else to ask it. I want to make a website that lets the user upload a file and then make the file available to be downloaded by another user. I have finished the frontend to backend upload so the file is available in the Django backend. I plan to manually encrypt the file in the backend before saving it to database. I also plan to save the bytes of the file to the database instead of the actual file, for example: uploadedFile = request.FILES["file"] file_data = [] for chunk in uploadedFile.chunks(): file_data.append(chunk) # Encrypt file_data... # Save file_data to database here... The problem is that after I decrypt the bytes of the file, how do I convert the file bytes to an actual downloadable file? (basically the opposite of file.read() in Django) Does anyone know how to do this, and please edit this question or ask if anything is unclear. Thank you. -
Latest objects of every group with Django filter in mysql backend
I have 2 Models- class WLSDomainName(BaseMixin): domain_name = models.CharField('Domain Name',max_length=255, null=False, blank=False) site_name = models.CharField('Site Name', max_length=10, choices = SITE_NAME, default='dc',blank=False, null=False) delete_status = models.BooleanField(default=False) class DomainOverallHealthStatus(BaseMixin): domain_name = models.ForeignKey(WLSDomainName, on_delete=models.CASCADE, null=True, blank=False, related_name="overall_health_status_domain_name") configuredServerCount = models.IntegerField(blank=True, null=True) activeServerCount = models.IntegerField(blank=True, null=True) overallServiceHealth = models.CharField(max_length=255, null=True, blank=True) activeThreadCount = models.IntegerField(blank=True, null=True) activeHttpSessionCount = models.IntegerField(blank=True, null=True) classification_time = models.CharField(max_length=20, null=True, blank=True) I need to find the latest object from DomainOverallHealthStatus model for every object of WLSDomainName. I have tried- o_health = DomainOverallHealthStatus.objects.all().values('domain_name').annotate(Max('created')).order_by() This query returning me only id and created. <QuerySet [{'domain_name': 1, 'created__max': datetime.datetime(2022, 8, 31, 9, 14, 49, 217073, tzinfo=datetime.timezone.utc)}, {'domain_name': 2, 'created__max': datetime.datetime(2022, 8, 31, 9, 14, 50, 338368, tzinfo=datetime.timezone.utc)}]> But I need to fetch every column of DomainOverallHealthStatus. Thanks in advance. -
Host blocking SMTP connection [closed]
I'm working on a django/python API. I've been trying to configure smtp settings but it's refusing connection to the host. I've tried running the telnet command, turning off my firewall, and created an inbound rule but still nothing works. Any help? -
Issue in making a Pie Chart using django with fully dynamic data
I have a Django backend that is sending this dict : {'New': 1, 'Pending': 0, 'Done': 0} I have to make a pie chart with this, So I tried: labels: ["{% for key, value in pie.items %}{{key}}{% endfor %}"] and the output is "NewPendingDone" instead of New, Pending, Done My Full code is : var config = { type: 'pie', data: { datasets: [{ data: ["{% for key, value in pie.items %}{{value}}{% endfor %}"], backgroundColor: [ '#dc3912', '#ff9900', '#3366cc' ], label: '' }], labels: ["{% for key, value in pie.items %}{{key}}{% endfor %}"] <-- here }, options: { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: '' } } } }; Here's the ss of the current situation. Pie Chart -
Django Postgres database with multiple schema. How to add records to specific schema through shell
Iam currently working on django multi tenant using shared database with multiple schema approach. How can I add records to specific schema through shell.How can I get the specific schema database objects in views.py -
Django (DRF) crashing when creating shapely LineString
I have an Django based Rest API application using DRF. On one endpoint an shapely Linestring is created from a list of tuples containing 2d coordinates. When creating the linestring with more than two points the application crashes without error message. # works fine data = [(430739.78125, 5642007.5), (430662.03, 5642191.5)] # not working data = [(430739.78125, 5642007.5), (430662.03, 5642191.5), (430623.1, 5642283.0)] I have already reinstalled all dependencies but could not solve the issue. -
how to serialize when fields are not known in django-rest-framework?
I want to serialize a dictionary where field_name is not fixed, it can be anything and i need to validate if type of field_value is correct according to what type should be provided to field_name. e.g: { "attributes": { attribute_name: attribute_vale . . . (can contain such more pairs) } } Is there any serializer way that can help me to serialize the key-value pair of attributes dictionary? -
Attribute Error: 'QuerySet' object has no attribute 'name'
in my Django project, I have a list of items where users specify categories while submitting "Crate New Item" form. The default route shows this list of items with the title, description and category of the item. Users can click on each category to be redirected to that related category's page where I'm trying to display all items under that category. To do that, I want to check if the category submitted in the form is already in our Category database. If yes, the item should be added under the existing category's page and if not, a new category should be created. However, I get an attribute error while trying to check that and I'm stuck. Would appreciate any help. AttributeError at /create 'QuerySet' object has no attribute 'name' models.py: class User(AbstractUser): pass class Category(models.Model): name = models.CharField(max_length = 64, null = True) class AuctionItem(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "created_by") title = models.CharField(max_length = 64) description = models.TextField() price = models.DecimalField(max_digits = 100 ,decimal_places = 2) image = models.URLField(blank = True) category = models.ForeignKey(Category, on_delete = models.CASCADE, related_name = "item_category") date = models.DateTimeField(auto_now_add = True) urls.py: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", … -
How to get list as a value from another model of a serializer key's value in DRF serializer?
Models: class SellerHub(BaseModel): name = models.CharField(blank=False, max_length=255) address = models.TextField( blank=True, ) status = models.BooleanField(default=True) contact_person = models.CharField(blank=False, max_length=255) hub_type = models.ForeignKey(SellerHubType, on_delete=models.CASCADE) latitude = models.DecimalField( max_digits=22, decimal_places=16, blank=True, null=True ) longitude = models.DecimalField( max_digits=22, decimal_places=16, blank=True, null=True ) image = models.ImageField( default="default_images/default_seller_hub.png", upload_to=seller_hub_image_path, ) status = models.BooleanField(default=True) class Meta: app_label = "seller_hub" def __str__(self): return self.name class SellerHubPhone(BaseModel): seller_hub = models.ForeignKey(SellerHub, on_delete=models.CASCADE) phone = PhoneNumberField(blank=False, max_length=255) status = models.BooleanField(default=True) def __str__(self): return f"{str(self.phone)} for {self.seller_hub.name}" Serializers: from rest_framework import serializers from seller_hub.selectors import seller_phone from phonenumber_field.serializerfields import PhoneNumberField class SellerHubPhoneSerializer(serializers.Serializer): phone = PhoneNumberField() class SellerHubSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField(max_length=255) address = serializers.CharField() image = serializers.ImageField() phone = serializers.SerializerMethodField("get_phone") def get_phone(self, obj): hub_phone = seller_phone(obj) # Returns a queryset of SellerHubPhone objects print("Phone: ", hub_phone) serializer = SellerHubPhoneSerializer(hub_phone, many=True) return serializer.data This is my current output: "data": [ { "id": 1, "name": "Test Seller Hub", "address": "Test seller Address", "image": "http://127.0.0.1:8000/media/default_images/default_seller_hub.png", "phone": [ { "phone": "+8801777777777" }, { "phone": "+491783379222" } ] } ] Expected Output: "data": [ { "id": 1, "name": "Test Seller Hub", "address": "Test seller Address", "image": "http://127.0.0.1:8000/media/default_images/default_seller_hub.png", "phone": [ "+8801777777777", "+491783379222" ] } ] Here SellerHub might have multiple phone numbers, so I am … -
How to run crontab in docker container with django?
Currently i am run python3 manage.py crontab add in docker bash,but cron not run. Please check the screenshot here cron adding message show but also return /bin/sh: 1: /usr/bin/crontab: not found error. -
Django django-two-factor-auth Error 'two_factor_tags' is not a registered tag library
I needed 2FA for my Staff members so I installed django-two-factor-auth But there seems to be an issue with the 'two_factor_tags' in core/login.html file Error message : 'two_factor_tags' is not a registered tag library . Must be one of: admin_list admin_modify admin_urls cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils example i18n l10n log static tz Using : Django==4.1 django-otp==1.1.3 django-phonenumber-field==6.4.0 django-two-factor-auth==1.14.0 phonenumbers==8.12.54 Any help is much appreciated. I did remove the tag from the code but it might bug my entire login system. -
Django Celery calling redis but I am using RabbitMq as Message broker
I am using celery and RabbitMq as message broker with Django and Docker. after putting my docker image up I run the following command: docker-compose run --rm web bash to enter my container and then I run: celery -A wine_shop worker --loglevel=info instead of getting a confirmation that my borker is working I get the following message: [2022-08-31 09:30:57,796: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6380//: Error 99 connecting to localhost:6380. Cannot assign requested address.. Trying again in 2.00 seconds... (1/100) I can notice that the transport is wrong, it should be calling the py-amqp transport but it's calling redis. -------------- celery@4c40607a9f71 v5.2.6 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.0-46-generic-x86_64-with-glibc2.31 2022-08-31 09:30:57 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: wine_shop:0x7f2546178460 - ** ---------- .> transport: redis://localhost:6380// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Any ideas on how to solve it? Down here you can find my configuration files: Settings.py from pathlib import Path import os from decouple import config # Build paths … -
getting error in django models while using foreign key
I am using foreign key in django models. But getting error. models.py: class subscription(models.Model): duration_choice = ( ("Monthly", "Monthly"), ("1 Year", "1 Year"), ("2 Year", "2 Year"), ) Duration = models.CharField(max_length=100,choices=duration_choice) Price=models.IntegerField(default=0) def __str__(self): return self.Duration class pro_Members(models.Model): subscription_type = models.ForeignKey(subscription,on_delete=models.CASCADE, default="") start_date=models.DateField(blank=True, null=True) expire_date= models.DateField(blank=True, null=True) is_active=models.BooleanField(default=False) I used subscription models as foreign key in pro_members model. But getting an error. column firmApp_pro_members.subscription_type_id does not exist LINE 1: SELECT "firmApp_pro_members"."id", "firmApp_pro_members"."su... anyone here can help. I tried my best but can not solve it. -
Django return, Profile matching query does nor exit
I'm new to Django and I'm working on an Instagram clone project as a beginner. And I didn't get this error. I imported the user The Profile class is created here, and it is successfully migrated. and this is my views.py someone please answers this where is my mistake? -
Is the server running on that host and accepting TCP/IP connections?
I am working on a Django project as a Front-End developer. I am getting " django.db.utils.OperationalError: connection to server at "13.234.81.119", port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?" many times when I try to run the server using the command python manage.py runserver on VS Code Because of this, I have to restart the server, and sometimes luckily server works. I did the following things to resolve the problem: NOTE: I am using windows 11. 1) deleted temporary files using the command %temp% 2) reinstalled psycopg 2.9.2 3) I reset the TCP/IP settings in services on my PC. but the problem did not solve. I am attaching the screenshots of the complete error log. Please help me to resolve the issue, I will be grateful to you -
Nested serializer representation for PrimaryKeyRelatedField
I want to add and remove products to an order by only using their ids, but I want the order representation to look like a nested serializer. My Models: class Product(models.Model): title = models.CharField(max_length=200) price = models.DecimalField(max_digits=1_000, decimal_places=2) def __str__(self): return self.title class Order(models.Model): date = models.DateField() products = models.ManyToManyField(Product, blank=True, related_name='orders') My Serializers: class ProductSerializer(serializers.ModelSerializer): price = serializers.DecimalField(max_digits=1_000, decimal_places=2, coerce_to_string=False) class Meta: model = Product fields = ['id', 'title', 'price'] class OrderSerializer(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), many=True) class Meta: model = Order fields = ['id', 'date', 'products'] I'm trying to get the below representation: { "id": 1, "date": "2021-08-12", "products": [ { "id": 1, "title": "Item 1", "price": 19.99 }, { "id": 3, "title": "Item 3", "price": 49.99 } ] } However, if I want to create the above order the json should look like this: { "date": "2021-08-12", "products":[1, 3] } And if I want to add a product with id==2 to the above order it should look like this: { "id": 1, "date": "2021-08-12", "products":[1, 3, 2] } I've tried overriding the to_representation() method and adding a nested serializer there, but I have no idea how to go about it. Should it look something like this, or am … -
being able to encode url parameters in django template while using url tag to prevent NoReverseMatch error
I'm writing a project with python 3.10 and django 4.1 I defined the following route: app_name = 'admin_extend' urlpatterns = [ path('add_fav/<str:name>/<str:add_url>/<str:admin_url>/', views.add_fav, name='add_fav'), ] now i have 3 parameters here, name, add_url and admin_url. both add_url and admin_url contains '/' so i need to be able to escape them in the django template. this is my code in the template: <a href="{% url 'admin_extend:add_fav' name=model.name add_url=model.add_url admin_url=model.admin_url %}" class="changelink">{% translate 'Fav' %}</a> lets say the parameters value are name='foo', add_url='/a/b/c/', admin_url='/c/d/e/', the route fails with NoReverseMatch: Reverse for 'add_fav' with keyword arguments '{'name': 'foo', 'add_url': '/a/b/c/', 'admin_url': '/c/d/e/'}' not found. 1 pattern(s) tried: ['admin_extend/add_fav/(?P<name>[^/]+)/(?P<add_url>[^/]+)/(?P<admin_url>[^/]+)/\\Z'] i tested it and if i provide the parameters without / characters then i get no error. my problem is i really can't find anywhere how to escape these parameters, i googled and checked on stackoverflow a lot for example i can't use the {% filter urlencode %} before and after because the url needs to be validated first and then it will go through the urlencode, i learned that i can't run python code in these templates so i can't use urlqoute from django.utils.http and using urlencode filter in this way is not a … -
Django: Why model manager (objects) get_queryset() method executes during initialization phase?
I'm building a SAAS site, which currently uses django_tenants with postgresql for a physical separation of tenants into different schemas. I've decided to move everything into a single schema and impliment logical data separation instead. During my proof-of-concept phase, I've added a new middleware with the new tenant logic, and left the existing middleware (from django_tenants) in place. From my settings: MIDDLEWARE = [ 'tenants.middleware.main.TenantMainMiddleware', 'utilities.middleware.TenantMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] The existing one from django_tenants is the first one: TenantMainMiddleware - my new one is the next line down: TenantMiddleware Basically, I will add a ForeignKey field to each model that needs tenant separation, and my middleware will load the appropriate tenant instance based on the subdomain part of the domain. For example: demo.mysite.com - will cause a lookup on "demo" in the tenant table. The resulting tenant object will be added to the request object, which is, in turn, stored in thread local storage. Here's my middleware: class TenantMiddleware(MiddlewareMixin): def process_request(self, request): current_tenant = connection.tenant # This is temporary to connection.set_schema_to_public() # allow the existing subdomain = self.get_subdomain_from_request(request) # tenant code to still work try: tenant = VTenant.objects.get(subdomain__iexact=subdomain) except VTenant.DoesNotExist: raise APIInvalidRequest(_('No tenant for subdomain … -
Models PhoneNumberField Not Recognizing
thank you very much for your help. i had restframework api application and i want to store user phone number but wouldn't store it as CharField or TextField. i want to use PhoneNumberField django package. I got installed: django-phonenumber-field==5.0.0 phonenumberslite==8.12.11 but still i got this err in makemigrations my project Traceback (most recent call last): File "C:\Users\moham\OneDrive\Projects\UpMenu\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'phonenumber_field' That's my models.py: import uuid from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Users(models.Model): owner = models.ForeignKey( "auth.User", related_name="snippets", on_delete=models.CASCADE, null=True ) Id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) Email = models.EmailField(unique=True) Password = models.CharField(max_length=50) FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Address = models.CharField(max_length=250) CellPhone = PhoneNumberField() EmailActiveCode = models.BooleanField(default=False) IsActived = models.BooleanField(default=False) IsDelete = models.BooleanField(default=False) … -
parsing rss tag <**:**> by feedparser
I have rdf which has <dc:date> and <dc:subject> When parsing import feedparser d = feedparser.parse(link_url) for e in d.entries: print(e.date) print(e.subject) e.date works but e.subject doesn't work. Why does this happen? how can I use <**:**> tag? -
How to add a named link instead of add+ to add in Django Admin
That's the default way of doing things in Django admin I want to remove add button and want to add a link like that Figma Design How I can achieve that ? -
How to get url for htmx get from an SSE event which itself triggers the hx-get call?
I am using django with django-channels and htmx. In certain cases, my django views will send an SSE event to a user subscribed to the relevant channel, like a notification for example. Some of those events (depending on event name) needs to trigger a modal pop-up (like a rating modal after an e-commerce order or service completes). I have implemented the requirements of the server-side event and data generation. I want to use the htmx sse extension on the frontend (django template). My problem is, I want to get an event, let's say order_complete, and use that to trigger an hx-get call to a particular url which will be sent by the sse event. That hx-get's response will then be placed in the placeholder where modal view logic exists. I have very little knowledge of JavaScript and not all that much more on htmx. I've looked at out of band swaps but I'm not sure if that's what I need. I'd appreciate any opinion or suggestions for proceeding including a non-htmx solution if it's better performing or easier. Thank you. -
How to show live streaming camera videos in django rest framework
I am building a application in django rest framework and frontend in react i want to shows streaming of multiple live camera into browsers there is any way how we can achieve it using openCV or how we can genrate response with stream of bytes in django rest framework -
Django Admin Custom Queryset. prevent e=1
I have a need to enter product ids in the url of my admin page but Django does not allow me to. This is my function that does work. def get_queryset(self, request): qs = super(LaptopStockAdmin, self).get_queryset(request) pid = request.GET.get('pid') if pid is not None: ids = [int(id) for id in pid.split(',')] return qs.filter(id__in=ids) else: return qs It gets the objects related to the ids but then Django refreshes the page and ads ?e=1 after the URL. This is a security related problem and I cannot find a suitable solution. I have tried these methods but they don't work for my specific case. Is there a way to not create a list filter and where the results are shown in the admin page?