Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Amazon SES with dynamic credentials?
I'm using Django/Python and I want to use multiple Amazon SES credentials on same server. I found boto3 to consume Amazon APIs but it requires to set the credentials using a file or environment variables. Which is I can't (or it's hard to) change it in the runtime. How can I set the credentials dynamically on runtime? I'm looking for a solution something like that: (boto3 is not mandatory, I can use any solution) CREDS = { "foo": { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX", "AWS_DEFAULT_REGION": "us-east-1", }, "bar": { "AWS_ACCESS_KEY_ID": "YYY", "AWS_SECRET_ACCESS_KEY": "YYY", "AWS_DEFAULT_REGION": "us-east-1", }, } my_config = CREDS.get("foo") # or "bar" client = boto3.client('ses', config=my_config) How can I implement this? -
How to obtain a restaurant open hours in Django with reactjs
I would like to stock the schedules of my restaurants' list. What is the name of the field who can i do that: for example, the restaurants is open on Monday from 9 am to 11 pm. Can I do that? Thanks -
Why do the queries that I send ordered to the template from the django view arrive out of order?
I am making a query to the database, ordering it by date and then sending it to the template. The problem is that the query arrives out of order to the template This is the query from the view: recibos=grupo.recibos.all().order_by('-fecha_pago') This is the template code: {% if recibos %} <table class="table table-responsive-sm table-sm table-hover datatable"> <thead> <tr> <th>Responsable</th> <th class="text-center">Fecha</th> <th class="text-center">Monto</th> <th class="text-center">Forma de Pago</th> <th class="text-center"></th> </tr> </thead> <tbody> {% for recibo in recibos %} <tr> <td> <div>{{recibo.responsable.nombre}}</div> </td> <td class="text-center"> <div>{{recibo.fecha_pago}}</div> </td> <td class="text-center"> <div>${{recibo.importe|floatformat:"2g"}}</div> </td> <td class="text-center"> <div>{{recibo.forma_pago}}</div> </td> <td class="text-center"> <div>botones</div> </td> </tr> {% endfor %} </tbody> </table> {% endif %} -
What is the best way to validate data in Django REST framework?
I have tried validating incoming data in my serializer depending on the necessary validation. is there any standard I should follow when I am doing this. -
how can I add sidebar items
I'm doing control panel right now and how can I add sidebar items in django control panel, I searched I find some info but none of them how they add ready control panel? -
Gunicorn + Nginx - Resource temporarily unavailable while connecting to upstream
We are using gunicorn + supervisor + nginx to run django app using docker environment on beanstalk Issue is supervisor shows that gunicorn is up but all requests fails with 502 response code from nginx. Ideally I think supervisor should restart gunicorn process since it's not able to respond any request successfully. server_tokens off; upstream wsgi_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/run/django_app.sock fail_timeout=0; } server { location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Protocol $http_x_forwarded_proto; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 60s; proxy_read_timeout 60s; proxy_pass http://wsgi_server; } } 2022/10/10 12:35:26 [error] 21#21: *728396 connect() to unix:/run/django_app.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 172.31.53.68, server: *.service.vpc, request: "GET /user/ HTTP/1.1", upstream: "http://unix:/run/django_app.sock:/user/", host: "service.vpc" Additionally, How to debug hanged gunicorn worker to figure out where exactly the problem lies ? -
how do solve import error in django project
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable i have activated the virtualenv on many but yet I can't run the server -
Django/SQLite : Converting event-wise table to timeserie
I have a SQLite database (with Django as ORM) with a table of recorded change events (an Account is assigned a new Strategy). I would like to convert it to a timeserie, to be able to have on each day, the Strategy that the Account was following. Here is a preview of my table : and here is the expected output : For the sake of simplicity, I only showed one account as example but there is several, so a group by operation on account_id could be the start. Also, there can be more than 1 change/day. In this case, we select the last change of the day, as the desired timeserie output must have only one value per day. My question is completely similar to this one, but in SQL, not in BigQuery (and to be fully transparent I'm not entirely sure I understood properly what was hapenning in the unnest part they proposed). I have a working solution in pandas but it is very ugly (with reindex and fillna), and I'm quite sure there is an elegant and simple solution in SQL (or maybe even better with Django ORM). -
Django not showing new changes in production
I've changed env file and models.py for media app. When i check the files, the code shows the latest version, which is correct. When i visit the page, i don't see any changes. On my local environment i see the changes. I've done the following sudo systemctl restart nginx sudo systemctl restart uwsgi then i tried touch on uwsgi/admin.ini touch admin.ini sudo systemctl restart uwsgi then i deleted __pycache__ I restarted the instance and the changes aren't showing? I checked the env file and still using old credentials. There are no errors in the logs? How can i debug this? -
Django HttpResponseRedirect doesn´t lead to the page
I am working on the CS50 project2 commerce. I try to create a new list but when I click on the submit button, it doesn´t redirect to the index page as I want. Anybody can help please? enter image description here def createlisting(request): if request.method == "GET": allCategories = Category.objects.all() return render(request, "auctions/create.html", { "categories": allCategories }) else: # get the data from the form title = request.POST["title"] description = request.POST["description"] imageurl = request.POST["imageurl"] price = request.POST["price"] category = request.POST["category"] currentuser = request.user # get the contents categoryData = Category.objects.get(categoryName=category) #create new list object newListing = Listing( title=title, description=description, imageUrl=imageurl, price=float(price), category=categoryData, owner=currentuser ) newListing.save() return HttpResponseRedirect(reverse("index")) -
How to Display or accept names instead of ids in Django Superadmin while using GenericFroeignKey
I have a model for my project which is using GenricFroeignKeys for adding Stakeholders to Projects and Reposistories both. The model is from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType class StakeHolder(models.Model): """Model class for Stakeholders of Project and Repos""" name = models.TextField() email = models.EmailField() def __str__(self): return self.name class Role(models.Model): """This is the model for Role that the stakeholders will have o projects and repos""" name = models.TextField() def __str__(self): return self.name class ProjectRepoStakeHolder(models.Model): """This is a generic models used to define stakeholders on project and repos""" stake_holder = models.ForeignKey(StakeHolder, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) limit = models.Q(app_label='pr_reviews', model='repository') | \ models.Q(app_label='pr_reviews', model='project') # Fields that are mandatory for generic relations content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit,) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.stake_holder.name + "/" + self.role.name + "/" + self.content_object.name class Project(models.Model): """Model class for Project""" name = models.TextField(unique=True, blank=False, null=False) uuid = models.UUIDField(unique=True, blank=False, null=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Repository(models.Model): """Model class for Repository""" project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=False, null=False) name = models.TextField(unique=True, blank=False, null=False) uuid = models.UUIDField(blank=False, null=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = … -
What are these unknown client errors on GAE instance?
I deployed Django Application on GAE. After that, I'm getting a client error on unknown files. Those files are below. I know only favicon.ico because I haven't uploaded it yet. But I don't know others. Almost of them look about WordPress. Are these client errors attacks for WordPress files on GAE? How can I stop these? Thank you. -
sqlfuction to django method
I have this postgresql function. Can I convert this function to django-method? I have implemented these functions in sql, but I would like to implement these functions so that they can be used in django or may I ask if there is a way to use the raw-query function separately in django? CREATE EXTENSION IF NOT EXISTS "pgcrypto"; DO $$ BEGIN CREATE DOMAIN SHORTKEY as varchar(11); EXCEPTION WHEN duplicate_object THEN null; END $$; CREATE OR REPLACE FUNCTION shortkey_generate() RETURNS TRIGGER AS $$ DECLARE gkey TEXT; key SHORTKEY; qry TEXT; found TEXT; user_id BOOLEAN; BEGIN qry := 'SELECT id FROM ' || quote_ident(TG_TABLE_NAME) || ' WHERE id='; LOOP IF NEW.id IS NOT NULL THEN key := NEW.company_id; user_id := TRUE; IF length(key) <> 11 THEN RAISE 'User defined key value % has invalid length. Expected 11, got %.', key, length(key); END IF; ELSE gkey := encode(gen_random_bytes(8), 'base64'); gkey := replace(gkey, '/', '_'); -- url safe replacement gkey := replace(gkey, '+', '-'); -- url safe replacement key := rtrim(gkey, '='); -- cut off padding user_id := FALSE; END IF; EXECUTE qry || quote_literal(key) INTO found; IF found IS NULL THEN EXIT; END IF; IF user_id THEN RAISE 'ID % already exists in … -
My django project is running correctly on Heroku but the WebSocket request is not going
My django project is running correctly on Heroku but the WebSocket request is not going in working properly in local environment asgi.py import os import django from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'espere.settings') django.setup() # application = get_asgi_application() django_asgi_app = get_asgi_application() import chat_app.routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( chat_app.routing.websocket_urlpatterns ) ) ), }) settings.py # WSGI_APPLICATION = 'espere.wsgi.application' ASGI_APPLICATION = 'espere.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } Procfile web: daphne espere.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker -v2 -
Django REST framework returning empty queryset even though the shell/print returns items
My JSON response to GET http://localhost:8000/v1/tags/search is [] But it should contain a list of tags. I've registered the route with DRF: router.register(r"tags/search", TagSearchViewSet, basename='tag-search-list') The view: from taggit.models import Tag class TagSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = TagSearchSerializer paginator = None def get_queryset(self): queryset = Tag.objects.all() print(queryset) return queryset The serializer: from taggit.models import Tag class TagSearchSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' That print() statement prints out <QuerySet [<Tag: something>, <Tag: else>, <Tag: mytag2>, <Tag: mytag1>, <Tag: mytag3>, <Tag: mytag4>]> In python manage.py shell I can also print out tags using > from taggit.models import Tag > tags = Tag.objects.all() > tags <QuerySet [<Tag: something>, <Tag: else>, <Tag: mytag2>, <Tag: mytag1>, <Tag: mytag3>, <Tag: mytag4>]> So why is the response an empty list? -
Control panel file manager
I'm making a basic panel with Django, I add sidebar, navbar some process but I need to add a file manager and I searched but couldn't find anything. Can you help me? -
Custom QuerySet for a Django admin action
# Customers model Customers(models.Model): name = models.CharField(max_length=255) emails = ArrayField(models.EmailField(), default=list, blank=True) ... ... ... I have a QuerySet which has all the information according to model of all the selected customers. # Django admin action def get_email_ids(self, request, queryset): """ QuerySet here is all the information according to model of all the selected customers. """ # new_queryset = ? return generate_csv( request, queryset, filename="email-ids.csv", ) I want a new custom QuerySet which only has the customer name and email id's. But it should be in the following way. If a customer has 10 email id's then there should be 10 rows for that customer in the QuerySet. e.g. customer1 email1@email.com customer1 email2@email.com customer1 email3@email.com customer1 email4@email.com customer2 emailother@email.com How to achieve this for new_queryset? -
keyword base Elastic Search Query
what changes i have to do in this query to searching. I'm working on open-edx project with django (python) and i want to implement elastic search in this project. I want to search courses by it's incomplete name like if there Robotics named courses will be find out if i only search ro, rob, robo, robot etc.... please help me ! enter: if search_term: filters = True search_result = searcher.search(search_term,field_dictionary=match_field_dict,size=20,from_=20*(int(page) if page else 0)) else: search_result = searcher.search(field_dictionary=match_field_dict,size=20,from_=20*(int(page) if page else 0)) [api.py file][1] [result1][2] [result2][3] [1]: https://i.stack.imgur.com/JhfW7.png [2]: https://i.stack.imgur.com/KpKb1.png [3]: https://i.stack.imgur.com/peiF2.png -
Django - List all objects that have one object as related field
I want to do something similar to the screen that shows in the Django admin panel when you are going to delete an object. The difference is that that screen shows every object that would be deleted because of the CASCADE effect. I would also like to get every object that has it related to SET_NULL or whatever option. The use case that I have is: lets say we have the tipical Author / Book class definitions (but with many more objects that have Author as a foreign key). Now we have two Author objects that we want to merge into one of them only because the second one is a variation with wrong information. I want to be able to say to every object that was the wrong author object to relate to the correct one before deleting the bad one. I know I can do it manually checking every model that has Author as foreign key and updating it. But is there a built-in function or similar to get all at once? -
Errors in Migrating models
Having errors in trying to migrate models(makemigrations command). Errors in classes Cart and Product. Here's the code: class Cart(models.Model): type_status = (('Pending'), ('Ongoing'), ('Delivered')) type_payment = (('Yes'), ('No')) cart_id = models.AutoField(primary_key=True) status = models.CharField(max_length=1, choices=type_status) payment_paid = models.CharField(max_length=1, choices=type_payment) totalAmount = models.FloatField() class Product(models.Model): item_id = models.ForeignKey(Admin, on_delete=models.CASCADE) itemName = models.ForeignKey(Admin, on_delete=models.CASCADE) price = models.FloatField() ERRORS: registration.Cart.payment_paid: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. registration.Cart.status: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. registration.Product.itemName: (fields.E304) Reverse accessor 'Admin.product_set' for 'registration.Product.itemName' clashes with reverse accessor for 'registration.Product.item_id'. HINT: Add or change a related_name argument to the definition for 'registration.Product.itemName' or 'registration.Product.item_id'. registration.Product.item_id: (fields.E304) Reverse accessor 'Admin.product_set' for 'registration.Product.item_id' clashes with reverse accessor for 'registration.Product.itemName'. HINT: Add or change a related_name argument to the definition for 'registration.Product.item_id' or 'registration.Product.itemName'. -
DRF: Integer expected but received String (using Axios)
I receive the following error when i try to send an array of id's to the django rest framework: My payload looks like: assigned_facilities: 1,2 When i using the drf api test page it works and the payload looks like this: assigned_facilities : [1, 2] So my assumption is that i'm missing the brackets and thats why it isn't working? How do i fix that? const cpBoard = useSelector((state) => state.cpBoard); const facilityIds = (cpBoard.cpBoardItems?.map(cpBoardItem => (cpBoardItem.id))); function submitFacilities() { const facilitydata = new FormData() facilitydata.append("assigned_facilities", facilityIds); axios.patch(API.leads.update(id), facilitydata, { headers: { "Authorization": `Bearer ${accessToken}`, 'Content-Type' : 'application/x-www-form-urlencoded', 'Accept' : 'application/json', }, withCredentials: true, }) .then(res => { setLead(res.data) }) .finally(() => { setLoading(false) }) } -
Submitting two forms with ajax independently with Django
Im trying to submit two POST forms with Django using ajax, but just one of the forms has the method POST in it. I dont really know what to do here, the error is probably in the Javascript, but i dont see why the first form submit with POST method and the second doesn't, i tried to search in the internet but i think i didnt search the right question. (sorry for my bad english) views.py import os import time from datetime import datetime from django.http import HttpResponse, StreamingHttpResponse from django.shortcuts import render from utils.camera_streaming_widget import CameraStreamingWidget # Camera feed def camera_feed(request): stream = CameraStreamingWidget() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') def detect(request): stream = CameraStreamingWidget() success, frame = stream.camera.read() if success: status = True else: status = False return render(request, 'detect_barcodes/detect.html', context={'cam_status': status}) def dados(request): if request.method == 'POST': name = request.POST['name'] print('HELLO') return HttpResponse(name) def dados_cod(request): if request.method == 'POST': cod = request.POST['cod'] print(cod) return HttpResponse(cod) html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" ></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <title>Detect Barcodes</title> <style type="text/css"> .navbar-brand { font-size: xx-large; } </style> </head> <body> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #3c8f56;"> <div … -
How to erase/delete/wipe the migration history in Django
I'm experimenting with varios django modells and settings. I can't erase the migration history which is make me upset. I have run this script and physically delete all .pyc files and the database. del /s /q *.pyc del /q db.sqlite3 After i typed: python manage.py makemigrations and i have got this: No changes detected I tired this as well: python manage.py migrate --fake-initial no luck. Any idea please! Thank you. -
Django template vs React
I am asked to build a mid-sized CRM using python, but I am not sure what to use to build that. Here are my questions: Should I follow the SPA approach? Should I use Django template or it is better to use Django REST framework to transmit the data as JSON to/from React? If it is better to use REST, is there any benefits of using Django over other Python web development frameworks like flask? -
Users erratically getting CancelledError with Django ASGI
Our users are erratically getting CancelledError for any page in our system. The only pattern we’ve observed is that this happens more often for pages which take more time to load during normal operation. But it is absolutely not limited to such pages, it can happen anywhere in our system, e.g. login page. All of the affected pages do not use any async code or channels, they’re standard django views working in request/response model (we migrated to ASGI only recently and we only have a single page which uses channels and it works just fine). We cannot reproduce it consistently. What we see in sentry.io: CancelledError: null File "channels/http.py", line 198, in __call__ await self.handle(scope, async_to_sync(send), body_stream) File "asgiref/sync.py", line 435, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "asyncio/tasks.py", line 414, in wait_for return await fut Locally and in Daphne logs it look like it: 2022-10-12 20:00:00,000 WARNING Application instance <Task pending coro=<ProtocolTypeRouter.__call__() running at /home/deploy/.virtualenvs/…/lib/python3.7/site-packages/channels/routing.py:71> wait_for=<Future pending cb=[_chain_future.._call_check_cancel() at /usr/lib/python3.7/asyncio/futures.py:348, <Task WakeupMethWrapper object at 0x7f1adcbf9610>()]>> for connection <WebRequest at 0x7f1adcc6bb50 method=POST uri=/dajaxice/operations.views.calculate_cost_view/ clientproto=HTTP/1.0> took too long to shut down and was killed. 2022-10-12 20:00:00,000 WARNING Application timed out while sending response From the user’s POV, the page simply …