Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query to sum first value in a nested fforeign key
Given the three below models class GrandFather(models.Model): pass class Father(models.Model): grandfather = models.ForeignKey(GrandFather) class Son(models.Model): father = models.ForeignKey(Father) date = models.DateField() value = models.IntegerField() What would the annotate command be to get the sum of the value of the latest son for each father, for all fathers in a grandfather. I can do a subquery, but don't know how to do a nested subquery. Don't know how to even go at that! -
Has anyone been able to deploy a Django project to elasticbeanstalk by uploading a zip file?
I have been able to deploy django projects using: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html , which is deployment from terminal on my mac. But I haven’t been able to do it by uploading a zip file. “ebdjango” is the name of my project. django.config contains: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application requirements.txt contains: asgiref==3.7.2 Django==4.2.9 sqlparse==0.4.4 typing_extensions==4.9.0 I am not sure if there is something wrong with how I create the zip file because i get the warning message: “Configuration files cannot be extracted from the application version ebdjango. Check that the application version is a valid zip or war file.” What I do is I compress .ebextensions, ebdjango manage.py and requirements.txt . When I open the zip file there is a root folder with the same name as the zip file and that folder contains .ebextensions, ebdjango manage.py and requirements.txt . Is it supposed to be like that or is everything supposed to be extracted from the zip when i open it without a parent folder? Is this why I can’t deploy my django project to elasticbeanstalk? -
Django ORM: "TypeError: 'list' object is not callable"
I've added class methods for the model. After adding them, it stopped working, gives me a type error. Migrations also don't work. These classes calculate the price with and without discount. Now quantity throws an error, suddenly becoming a 'list' object models class OrderItem(models.Model): price = models.DecimalField(max_digits=9, decimal_places=2) quantity = models.IntegerField(default=1) order = models.ForeignKey( Order, on_delete=models.CASCADE, blank=True, null=True, related_name='items') product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "Item" + str(self.id) def get_cost(self): return self.price * self.quantity @property def total_cost(self): return self.price * self.quantity @classmethod def get_total_quantity_for_product(cls, product): return cls.objects.filter(product=product).aggregate(total_quantity=models.Sum('quantity'))[ 'total_quantity'] or 0 @staticmethod def get_average_price(): return OrderItem.objects.aggregate(average_price=models.Avg('price'))['average_price'] admin.py code import csv import datetime from django.contrib import admin from django.http import HttpResponse from django.urls import reverse from django.utils.html import format_html from django.utils.safestring import mark_safe from .models import Order, OrderItem, ShippingAddress def export_paid_to_csv(modeladmin, request, queryset): opts = modeladmin.model._meta content_disposition = f"attachment; filename=Paid{opts.verbose_name}.csv" response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = content_disposition writer = csv.writer(response) fields = [ field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many ] writer.writerow([field.verbose_name for field in fields]) for obj in queryset: if not getattr(obj, "paid"): continue data_row = [] for field in fields: value = getattr(obj, field.name) if isinstance(value, … -
django get duplicated row pk
My goal is to update every day my database records by uploading a file containing the 7 past days data. If a record already exists, I would like to update it with the new one in the file we are uploading, otherwise create a new record and save it. An existing record is when we have the same date, the same advertiser, and the same insertion_order. I no more want to raise an exception error about those duplicated rows but handling them by updating them with the news ones. Could you please help me ? try: df.to_sql( dsp, # Xandr._meta.db_table, if_exists="append", index=False, dtype=dtype, chunksize=1000, con=engine, ) except IntegrityError: msg = "Duplicated rows are not authorized." raise Exception(msg) the model class Xandr(InsertionOrdersCommonFields): dsp = models.CharField("Xandr", max_length=20) class Meta: db_table = "Xandr" unique_together = [ "date", "advertiser", "insertion_order" ] verbose_name_plural = "Xandr" def __str__(self): return self.dsp The error I got -
Celery & Django - does the main process wait for tasks to finish?
I've just started work on a project that uses Django & Celery. I'm quite new to both. One of the endpoints has code that looks like this: task_make_report.delay() return Response( {"success": True}, status=status.HTTP_200_OK ) task_make_report is a task that takes a while to complete. (It does not call any other Celery tasks.) Will the main process execute the return statement immediately after Celery queues the task? Or will it wait for the task to be complete before moving on to the next line? Reading through the documentation, I'm inclined to think that the answer would be the first option (execute next statement after the task is queued), because Celery tasks are asynchronous. But I'd like to double-check. -
Google auth in react js(npm vite)
I'm making a inventory system which requires to sign up using their google account. My problem is I don't know how to use google api request in npm vite. Does anyone know how to do it? As a beginner I don't know where to begin. My backend that I'm using is django. Meanwhile in the frontend is NPM vite. -
django-rest-framework authentication and permission. Prevent authenticated user from posting if user is is_staff=false, is_superuser=false
I have a class based APIVIEW and I want to prevent a normal user (isstaff=false, is_superuser=false) from creating a customer. class CustomerPageView(APIView): # permission_required = 'api.view_customer' permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get(self, request): customer = Customer.objects.all() # Check if there is a customer if not customer.exists(): return JsonResponse([], safe=False) customer_serializer = CustomerSerializer(customer, many=True) return JsonResponse(customer_serializer.data, safe=False) def post(self, request): data = json.loads(request.body.decode('utf-8')) company_name, contact_person, contact_number, company_address = data.values() company_name = company_name.strip() # Check if item exists chk_company_name = Customer.objects.filter(company_name__iexact=company_name) if chk_company_name: return JsonResponse({'label':'company_name', 'message':'Customer Already Exists'}, status=500) if len(company_name) == 0: return JsonResponse({'label':'company_name', 'message':'Invalid Entry'}, status=500) createCustomerInstance = Customer.objects.create( company_name=company_name, contact_person=contact_person, contact_number=contact_number, company_address=company_address, ) return JsonResponse({'message': f"Successfully added {company_name}", 'variant': 'success'}) enter image description here this user currently don't have any permissions. However when I logged in as normal user I can still create a customer. -
How to serialize many-to-many-to-one relationship in Django Rest Framework
I have a many-to-many-to-one relationship I would like to represent in DRF. I can get the relevant fields using a SerializerMethodField but it feels like there should be a cleaner way. Setup: from django.db import models from rest_framework import serializers class Textbook(models.Model): id = models.AutoField(primary_key=True) class ETextBook(models.Model): id = models.AutoField(primary_key=True) textbook = models.OneToOneField(Textbook, on_delete=CASCADE, related_name="etextbook") class Author(models.Model): id = models.AutoField(primary_key=True) textbooks = models.ManyToManyField(Textbook, related_name="authors") class ETextBookSerializer(serializers.ModelSerializer): class Meta: model = ETextBook fields = "__all__" Ugly working solution: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ("id", "textbooks", "etextbooks") etextbooks = serializers.SerializerMethodField() def get_etextbooks(self, obj): etextbooks = ETextbook.objects.filter(textbook__authors=obj) return ETextBookSerializer(etextbooks, many=True).data But what I'd really like to do is: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ("id", "textbooks", "etextbooks") etextbooks = ETextBookSerializer(source="textbooks.etextbook", many=True) but this raises a: Traceback (most recent call last): File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/rest_framework/fields.py", line 446, in get_attribute return get_attribute(instance, self.source_attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/rest_framework/fields.py", line 96, in get_attribute instance = getattr(instance, attr) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'ManyRelatedManager' object has no attribute 'etextbook' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/django/views/decorators/csrf.py", … -
django exclude for foreign Key related and count elements
is a representation the basic django model relations STATIONS_MODEL state name ROUTER ForeignKey(ROUTERS) TICKET_MODEL STATIONS ForeignKey(station, related_name"ticketforstation") softDelete = bool IN VIEW TEMPLATE context['stations'] = stations_model.objects.all() IN TEMPLATE {% for station in stations %} <div class="container"> {{station.name}} <span>{{station.ticketforstation.all.count}}</span> </div> {% endfor %} I needed count only SOFTDELETE is FALSE ALSO SIMILAR A IN TEMPLATE {% for station in stations %} <div class="container"> {{station.name}} <span>{{station.ticketforstation.(SOFTDELETED FALSE).count}}</span> </div> {% endfor %} I don't have idea as with resolved this... -
Django atomic block for create with an unique field
I have a model similar to the following: Class MyModel(models.Model): my_field = models.CharField(max_length=30, default='', unique = True) And the following code to create new instances of the model: with transaction.atomic(): try: instance, _ = MyModel.objects.select_for_update().get_or_create( my_field=value) except (IntegrityError, OperationalError): pass return instance As of my understanding, the entire table is locked by the select_for_update. Another alternative would be catching the UniqueConstraintError after it occurs. Is there any way, to avoid having an UniqueConstraintError, without locking the entire table? -
Connection Refused Error: [Errno 111] Connection refused - Getting error for Mailtrap SMTP
I am trying to register user which should send activation code to the dummy server. But while sending the post request from the Insomnia getting 500 internal error. And using Djoser for the email communication (authentication and authorization) Checked telnet to the smtp server telnet sandbox.smtp.mailtrap.io 2525 Trying 54.158.84.126... Connected to mailsend-smtp-classic-f3a4534c019a3e96.elb.us-east-1.amazonaws.com. Escape character is '^]'. 220 smtp.mailtrap.io ESMTP ready Backend settings EMAIL_HOST=sandbox.smtp.mailtrap.io EMAIL_PORT=2525 EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL = env("EMAIL_HOST") EMAIL_USE_TLS = True EMAIL_PORT = env("EMAIL_PORT") EMAIL_HOST_USER = env("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD") DAFAULT_FROM_EMAIL = "XXXX" DOMAIN = env("DOMAIN") SITE_NAME = "XXXX" DJOSER = { "LOGIN_FIELD": "email", "USER_CREATE_PASSWORD_RETYPE": True, "USERNAME_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "SEND_CONFIRMATION_EMAIL": True, "PASSWORD_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}", "SET_PASSWORD_RETYPE": True, "PASSWORD_RESET_CONFIRM_RETYPE": True, "USERNAME_RESET_CONFIRM_URL": "email/confirm/{uid}/{token}", "ACTIVATION_URL":"activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, } Not sure what is missing piece. -
Can't use custom hostname for Django app with runserver_plus
I'm running a Django application from a Docker container using docker compose. My goal is to run the application from a custom hostname, which I'll call myapp.com. Here are the steps I've taken thus far: Added 127.0.0.1 myapp.com to my /etc/hosts file Added a local CA using mkcert -install Created cert and key files using mkcert -cert-file cert.pem -key-file key.pem myapp.com 127.0.0.1 Added 'django_extensions' to the INSTALLED_APPS list in settings.py Added 'myapp.com' to the ALLOWED_HOSTS list in settings.py Set the startup command in docker-compose.yaml to python manage.py runserver_plus --cert-file cert.pem --key-file key.pem myapp.com:8000 When I start up the project with docker compose up, the server boots up successfully and the console claims that it's running with no issues at https://myapp.com:8000. However, attempting to actually access my application by visiting that URL does not work, giving an error page that says this: This site can't be reached myapp.com unexpectedly closed the connection. Attempting to curl that URL from my machine's command line also fails with this message, no matter what flags I use: curl: (35) schannel: failed to receive handshake, SSL/TLS connection failed However, running the curl command from within the docker container gives a different message (below) and running the … -
How to secure API server deployed in a DigitalOcean's droplet using HTTPS?
I have a project hosted on DigitalOcean and at the moment I have these clusters: My webpage (hosted in the wordpress droplet) is already secured through a SSL certificate and I can publicly access it via https://www.domain_name.it. However, my mobile application interacts with my Python Django API server that is deployed in the docker-ubuntu-droplet. An example of API resource that the mobile app uses is http://docker_droplet_IP:/api/get-customers/ I would like to secure API calls, such that the mobile application can use HTTPS protocol to safely transfer data (i.e. https://docker_droplet_IP:/api/get-customers/) but I am struggling finding out a way to do this, considering that the API server is called directly using the IP address. Can someone explain me how to proceed (and which steps should I make) to secure my Django API server? Thank you in advance. -
Python Geopy Library: Receiving 403 Error when Using Nominatim Geocoding Service – How to Resolve?
from geopy.geocoders import Nominatim def get_country(param): geolocator = Nominatim(user_agent="StampOcrApp") location = geolocator.geocode(param) place_entity = locationtagger.find_locations(text=location[0]) return check_entity(place_entity.countries) I m using get_country function and it throug 403 when this function is execute. Sometimes it work or sometimes it didn't work -
Dynamically add field to a Django Modelform
I have read all previous posts regarding this, but none of the solutions work for me, maybe its because Django has changed something? I want to add fields dynamically to my modelform, in the future it will be based of fetching some information from the backend to populate the fields, but right now I just want to show a field added in the init of the model form like so: class PackageFileInlineForm(forms.ModelForm): class Meta: model = File exclude = [] def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._meta.fields += self._meta.fields + ('test2',) self.fields['test2'] = forms.CharField() However the field is not shown when rendering the form. Why? -
autocomplete_fields wont work on ForeignKey from another app
I am new to Django I am using autocomplete_fields, Here is the Case. I have an app named Contacts where I am getting contact information and there is another app named school where I am Enrolling Contacts as person from my Contact app #models.py class FacultyRegistration(models.Model): role = models.ForeignKey(Roles, on_delete=models.CASCADE, null=True, verbose_name="Faculty Role") contact = models.ForeignKey('Contacts.Contact', related_name='faculty_Contact', on_delete=models.CASCADE) reference = models.ForeignKey('Contacts.Contact', on_delete=models.CASCADE, related_name='faculty_reference', ) Here I am registering person and using my Contact app for it #admin.py @admin.register(FacultyRegistration) class PersonRegistrationAdmin(admin.ModelAdmin): list_display = ('id', 'role', 'contact', 'reference') list_filter = ('role',) list_display_links = ('id', 'role', 'contact', 'reference', 'contact',) autocomplete_fields = ["role", 'contact', 'reference'] search_fields = ['role__person_role', 'contact__first_name', 'contact__middle_name', 'contact__last_name', 'reference__first_name', 'reference__middle_name', 'reference__last_name'] the issue is when I go to my admin panel I get searchable drop downs as expected but when I start typing to search my contact it wont fetch contacts enter image description here and it gives this error in console django.core.exceptions.FieldError: Unsupported lookup ‘icontains’ for ForeignKey or join on the field not permitted. [22/Jan/2024 12:33:08] “GET /autocomplete/?term=stu&app_label=school_app&model_name=facultyregistration&field_name=contact HTTP/1.1” 500 191958 however it works fine with my roles, maybe bcz roles are in same application -
DRF and GraphQL Mesh Integration using OpenAPI method?
I am relatively new to graphql-mesh and trying to understand. I have connected my graphql version of DRF to mesh and it worked but when I am trying to connect it using OpenAPI I get errors like graphql-mesh configuration package.json { "name": "graphql-mesh", "private": true, "scripts": { "dev": "mesh dev" }, "dependencies": { "@graphql-mesh/cli": "^0.88.5", "@graphql-mesh/graphql": "^0.96.3", "@graphql-mesh/openapi": "^0.97.5", "@graphql-mesh/runtime": "^0.97.4", "graphql": "^16.8.1" } } .meshrc.yml sources: - name: DeveloperGround handler: openapi: source: http://localhost:8000/swagger.json baseurl: http://localhost:8000 DRF configuration project/settings.py INSTALLED_APPS = [ ... 'drf_yasg', 'graphene_django', ] project/urls.py from graphene_django.views import GraphQLView schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Check description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('category/', include('mobiledeveloper.urls')), path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True))), path( "openapi<format>", drf_schema_view( title="Project", description="OpenAPI", version="1.0.0" ), name="openapi-schema", ), ] If I use graphql configuration for the mesh then it is working but not when using OpenAPI. There is no any authentication or authorization used. All the API request are AllowAny kind. And I have used OpenAPI of Stripe and it worked fine, so I am guessing here that my backend requires more work but i cannot figure out what kind of work is required. So … -
In Django tests, can I capture SQL from separate threads?
I have a lot of Django tests (using unittest) that capture the SQL queries of some operation and make various assertions against them. I'm now refactoring my code to introduce a threading.Timer, which executes some of the business logic in a callback after a certain amount of time. In my tests, I can force this callback to run instantly via, for example: def test_foobar(self): with self.CaptureQueriesContext(self.connection) as captured: foo = MyServiceWithATimer() foo.execute() foo.timer.finished.set() # force the timer to complete immediately # make various assertions here The problem is that CaptureQueriesContext now does not capture any of the SQL that ran in the Timer's callback. I've thought about alternative approaches such as not using threading.Timer at all, but these seem to require some sort of blocking while True event loop. Is there a way to make CaptureQueriesContext capture the SQL from child threads? -
How to sends custom status messages to the front end when the endpoint has some heavy process time, if I am using Django as backend?
this is a very general question. I was trying to look for something but here I might have a better start point. I am working with a python tool which is still on progress but the UI was done previously with PYQT5. What I wanted to do is creating some web front end (NextJs) and connecting with Django as backend and the calculations will be done on the local server we have. What I wanted to check is how I can send real time updates to the front end about the process that is happening on the backend. lets say if there is a loop, so sending the 1/10,2/10 and so on. Is this a socket thing (?) like streaming messages while is inside the http request. Thank you! I am still on the looking for options stage, what I have though is that this can be possible with sockets and emit messages from the backend to the front. -
I'm having trouble accessing Swagger; it shows 'The current path, swagger/, didn't match any of these' when I run the server
Error image I want to configure swagger with my project but. When i tried it throwing me error when ever I try I to run and i have configured properly everything in urls.py, file as shown in internet tutorial but don't know why I'm getting the current path is doesn't matching any of this. -
Can't open django admin from my live website in cPanel [too many redirects]
I am trying to open https://mywebsite.org/admin but it's responsing "This page isn’t working, mywebsite.org redirected you too many times. Try deleting your cookies. ERR_TOO_MANY_REDIRECTS." everything is working perfect in my local server. I'm facing this only on the live server in cPanel. All other tasks are working fine without the admin page. I am stuck for last 2 days on the same issue. I have tried most of the solutions available online . ensured static files transfered collect_static's admin folder to the public_html folder of cPanel checked all my urls used ADMIN_MEDIA_PREFIX = '/static/admin/' in the settings.py used whitenoise I am using deafult sqlite3 database of django. is that the issue? -
make sure that requests to my server come from my site and as a result of user interaction with it
I made a small react app that sends the following request to my server: const formData = new FormData(); formData.append('file', pdfFileSelected); formData.append('password', pdfPassword.current); formData.append('selected_pages', selectedPages); formData.append('save_separate', saveSeparate.current.checked) fetch('https://mydomain/pdf-processing/split/', { method: 'POST', body: formData }).then(response => response.json()) .then(data => console.log(data)); I have the server part on Django. But the problem is that someone can programmatically send such requests to my server. I know about the origin header in requests, but it can be modified in CLI scripts. I also tried the csrf token, but you can take it from the cookies of your browser and insert it into the form in your script. Are there any methods to verify that the request came from my domain and as a result of user interaction with the site? And if there are no such countermeasures to limit third-party requests to my server, then is it possible to simply limit the number of requests per day by IP? -
Programmatically create more workers at run-time by using Django_rq
I want to increase the number of workers in Django project by using Django_rq(Redis Queue) the problem is that I have to manually start each worker to complete the process in short time is their any way I can increase the number of workers or their number of process at the run time by using Django_rq? The problem is that queue which has large data takes time more even after optimization of code and cannot allow the other ids to processed until its queue with large data complete . It puts other ids in queue until large queue with data is completed. -
Nâng mũi cấu trúc bao lâu thì đẹp
Thường thường, quá trình ổn định và lên form đẹp của mũi sau phẫu thuật nâng mũi mất khoảng 1-3 tháng. Tuy nhiên, do nhiều yếu tố khác nhau, có những trường hợp mà việc đạt được đường nét dáng mũi mong muốn có thể kéo dài từ 3-6 tháng. Không có thời gian cụ thể để xác định khi nào mũi sẽ đạt đến hình dạng tự nhiên và đẹp mắt sau khi thực hiện phẫu thuật nâng mũi. Sau khi thực hiện phẫu thuật nâng mũi, thời gian cần để đạt được kết quả đẹp là một điều mà những người quan tâm đến thẩm mỹ mũi thường đặt ra. Tuy nhiên, để có cái nhìn toàn diện về vấn đề này, chúng ta cần hiểu rõ về các yếu tố liên quan và tác động trực tiếp lên quá trình hồi phục trước, trong và sau phẫu thuật. -
Django admin save_model
i'm new to django, please help me in below scenoria, when i save the order inn admin panel the same_model function not working the order is saving with out a function. The requirement is when i add order in admin panel when the quantity of orderedproduct is graeter the actual quantity it should through an error else it should reduce the ordered quantity from the product. The order is working but save_model function is not working admin.py from django.contrib import admin from django.contrib import messages from django.utils.translation import ngettext from .models import Category, Product, Order, OrderItem from django.utils.html import format_html class OrderItemInline(admin.TabularInline): model = OrderItem extra = 1 class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemInline] list_display = ('id', 'user', 'order_date') def save_model(self, request, obj, form, change): errors = [] super().save_model(request, obj, form, change) for order_item in obj.orderitem_set.all(): print(order_item.quantity) if order_item.quantity > order_item.product.quantity: errors.append( f"Order quantity ({order_item.quantity}) for {order_item.product.name} exceeds available quantity ({order_item.product.quantity})." ) else: order_item.product.quantity -= order_item.quantity order_item.product.save() if errors: # If there are errors, display a message and rollback the order creation message = ngettext( "The order was not saved due to the following error:", "The order was not saved due to the following errors:", len(errors), ) messages.error(request, f"{message} {', '.join(errors)}") …