Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Get latest related object for each object in queryset using one database query
I have a Django app where I collect data from sensors which are divided into areas. class Area(models.Model): name = models.CharField(max_length=50) code = models.IntegerField(unique=True, primary_key=True) class Sensor(models.Model): name = models.CharField(max_length=30) area = models.ForeignKey(Area, on_delete=models.CASCADE) class Observation(models.Model): date_time = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) value = models.DecimalField(max_digits=4, decimal_places=1) What I need for each area is a list of the latest observations in that area, that is, one per sensor. So far, I solved it like this: class Sensor(models.Model) ... def latest_observation(self): return self.observation_set.latest('date_time') Now, I can loop through my sensors to get the latest observation for each sensor. class Area(models.Model): ... def latest_observations_per_sensor(self): return [s.latest_observation() for s in self.sensor_set.all()] This returns a list of what I want, but it is not very efficient since it makes a database query for each individual sensor. Ideally, I would do this in one database query for all areas, but I don't know if this is possible in Django. -
how to sort django templates folder
i made my first blog templates in order blog/templates/sth.html becuz it didnt find in this order blog/templates/blog/sth.html but now i made a new app and made it in order users/templates/registiration/login.html and got this error Using engine django: django.template.loaders.app_directories.Loader: C:\Users\NDarksoul\.virtualenvs\blog-PCvr0qFP\lib\site-packages\django\contrib\admin\templates\blog\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\NDarksoul\.virtualenvs\blog-PCvr0qFP\lib\site-packages\django\contrib\auth\templates\blog\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\projects\rightnow\blog\blog\templates\blog\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\projects\rightnow\blog\users\templates\blog\base.html (Source does not exist) can u hlp me pls how to fix this mess -
djangosaml2 metadata and django settings
I am trying to change my login into SAML2 for a Django project. I just have a metadata URL where can I see the settings and the certificate for that. In that metadata, there is just one certificate content and ds:SignatureValue which is generating uniquely on every request. Do I also need a certificate key? And is there any way to get those settings directly from METADATA? https://login.entry.com/login/saml/idp/metadata <?xml version="1.0" encoding="UTF-8"?> <md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="_895c6e0e-1111-1111-1111-4eb316fa43cc" entityID="entity.com" validUntil="2026-12-29T09:54:08.000Z"> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> <ds:Reference URI="#_895c6e0e-2920-4a24-839f-4eb316fa43cc"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>RfLCex+sdsafdsfddsFDS+U=</ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue>FSdfsdFDSfds...==</ds:SignatureValue> </ds:Signature> <md:IDPSSODescriptor WantAuthnRequestsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> <md:KeyDescriptor use="signing"> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:X509Data> <ds:X509Certificate>MIIDezCCAmOgAwIBAgIEdKfywTANBgkqhkiG9w0Bx...==</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> </md:KeyDescriptor> <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat> <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://login.entity.com/login/saml/idp"/> <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://login.entity.com/login/saml/idp"/> </md:IDPSSODescriptor> </md:EntityDescriptor> -
How to fetch the data in react after redirecting django backend to react page with redirect function having data in it
I am working on an application with two parts as frontend and backend in react and django , I am using server side flow and using token authentication for login and authentication system with OAuth . When user clicks on the frontend on LOGIN WITH GOOGLE it is allowed to choose the email and login with the react server with port 3000 and the redirect url or callback url is my django backend with port 8080 and after i get the access token, get data from access token , and then I try to redirect to the frontend , that is also working , but how do i get the data in the frontend which i have passed from backend from redirect function , the data is passed but how do i access it in the front end . my views.py "http://localhost:8080/api/callback/" @api_view(["GET"]) def getCallBack(request , *args , **kwargs): if request.method == "GET" : data = { "scope" : request.GET.get("scope").strip().lstrip().rstrip() , "authuser" : request.GET.get("authuser").strip().lstrip().rstrip() , "prompt": request.GET.get("prompt").strip().lstrip().rstrip() , "code" : request.GET.get("code").strip().lstrip().rstrip() , "client_id" :"", "client_secret" : "", "redirect_uri" :"http://localhost:8080/api/callback/", "grant_type" :"authorization_code" } response = requests.post("https://accounts.google.com/o/oauth2/token" , data = data) token = response.json()["access_token"] payload = { "access_token" : token , } … -
Django - Add Object associated to another
I tried customizing a Django poll tutorial. I gave options so that users can add questions and options themselves. 'Choice' object from my models.py seems to be tricky. from django.db import models # Create your models here. class Question(models.Model): question = models.CharField(max_length=200) def __str__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices') option = models.CharField(max_length=100) vote = models.IntegerField(default=0) def __str__(self): return self.option Choice object is one-to-one relation with the Question. When I end values through the below HTML page, it doesn't create a new Choice. {% extends 'base.html' %} {% block content %} <h1>Add Member</h1> <form action = 'addoptrecord/' method='post'> {% csrf_token %} Choice: <br> <input name='ch'> <br> Vote: <br> <input name='vo'> <br> <label for="optquestions">Choose a Question:</label><br> <select name="optquestions" id="optquestions"> {% for question in questions %} <option value={{question.id}}>{{question}}</option> {%endfor%} </select><br><br> <input type='submit' value='Submit'> </form> {% endblock %} Not sure about the right syntax/method to associate the Choice data with Question while adding through views.py def addoptrecord(request,optquestions): ch = request.POST.get('ch') vo = request.POST.get('vo') que = Question.objects.get(id=optquestions) pollopt = Choice(que,option=ch,vote=vo) pollopt.save() return HttpResponseRedirect(reverse('index')) The above operation throughs me an Integrity Error. IntegrityError at /addopt/addoptrecord/ NOT NULL constraint failed: pollsapp_question.question -
Django - generic relation in django admin - is there any way to prefetch data, instead of making db query for every field in every row and column?
I have a following models (everything is simplified): class Car(models.Model): field_int = models.IntegerField(_('field_int'), null=True) field_datetime= models.DateTimeField(_('field_datetime')) field_boolean = models.BooleanField(_('field_boolean'), default=False) class Bus(models.Model): field_int = models.IntegerField(_('field_int'), null=False) field_datetime= models.DateTimeField(_('field_datetime')) field_boolean = models.BooleanField(_('field_boolean'), default=True) and I have something like vehicle report model with generic relation so I can "concatinate/merge" and show both models data simultaneously in django admin panel list_display class VehiclesReport(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: indexes = [ models.Index(fields=["content_type", "object_id"]), ] def field_int_generic(self): return self.content_object.field_int def field_datetime_generic(self): return self.content_object.field_datetime def field_boolean_generic(self): return self.content_object.field_boolean I am creating objects in script like this (this is example for Car but same for Bus class): VehiclesReport.objects.create( content_type=ContentType.objects.get_for_model(Car), object_id=car.object_id, ) and with all this models and data I created Admin panel so I can display everything at the same time: class VehiclesReportAdmin(ModelAdmin): list_display = ( 'field_int_generic', 'field_datetime_generic', 'field_boolean_generic', ) ordering = ('content_type',) admin_site.register(VehiclesReport, VehiclesReportAdmin) Everything work like charm but django instead of prefetching all data, it makes request for every field_int_generic, field_datetime_generic, field_boolean_generic execution, even when it is still the same "row". Lets say I have 'VehiclesReportAdmin' but with 10 columns like field_int_generic and 20 page limit... I have 200 database queries for just 20 rows of … -
Advice on Django Roadmap
my first post here. I'm 43 and took learning web development this year. I've been doing a lot of studying and practicing HTML CSS and started on JS. I've taken a few python courses in the past and really love the language. should I learn js fundamentals and a framework before moving to Django because it is the basis of the internet? and I can't seem to find anything on if there's a possibility to do simple front-end stuff with django. Any advice would be greatly appreciated. Ty in advance. -
how to not let staff or admin users edit superusers
I'm working on permission distribution and according to my user model structure, staff and admin users are allowed to edit is_staff and is_admin for other users, not themselves. But with such power, they are able to edit those booleans for superusers too, which I don't them to have permission for! so, how do I let staff and admin users edit those booleans for others except superusers and themselves? or to not let staff and admin users get permission to tamper with any superuser attributes admin def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser is_admin = request.user.is_admin disabled_fields = set() if ( not is_superuser and obj is not None and obj == request.user ): disabled_fields |= { 'staff', 'admin', 'user_permissions', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form -
Django Rest Framework - Serialize nested objects
I have this JSON input which I'd like to express properly in the Django Model in order to be correctly serialized by Django Rest Framework. the MainObject has name property and a list of conditions; each Condition is composed exactly by 2 blocks: left and right; each Block is composed by 1 field title and a list of user_params. { "name": "The Main Object Name", "conditions": [ { "left": { "title": "Title1", "user_params": [ { "name": "name_param_X", "value": "100" } ] }, "right": { "title": "Title2", "user_params": [ { "name": "name_param_Y", "value": "200" } ] } } ] } And here my models: class MainObject(models.Model): main_object_id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=64) class Condition(models.Model): condition_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) main_object = models.ForeignKey(MainObject, related_name="conditions", on_delete=models.CASCADE) left = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='left') right = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='right') class Block(models.Model): title = models.CharField(max_length=16, primary_key=True) class BlockParam(models.Model): name = models.CharField(max_length=32) value = models.IntegerField() block_title = models.ForeignKey(Block, related_name="user_params", on_delete=models.CASCADE) My serializers: class ConditionSerializer(serializers.ModelSerializer): condition_id = serializers.UUIDField(required=False) class Meta: model = Condition fields = ('condition_id', 'left', 'right') class MainObjectSerializer(serializers.ModelSerializer): conditions = ConditionSerializer(many=True) def create(self, validated_data): conditions_data = validated_data.pop("conditions") main_object = MainObject.objects.create(**validated_data) for condition_data in conditions_data: Condition.objects.create(main_object=main_object, **condition_data) return main_object The issue: when I … -
Connect javascript file with django in static file
I attach a js file to my Django but have problem bcz JS don't works on website view, when CSS file style Django see. I try looks some toturial but still the same problem. Arrow etc don;t react on any click. Terminal: [06/Oct/2022 11:11:50] "GET /home/ HTTP/1.1" 200 3381 [06/Oct/2022 11:11:50] "GET /static/css/style.css HTTP/1.1" 200 773 [06/Oct/2022 11:11:50] "GET /static/image/arrow-left.png HTTP/1.1" 200 375 [06/Oct/2022 11:11:50] "GET /static/image/arrow-right.png HTTP/1.1" 200 306 [06/Oct/2022 11:11:50] "GET /static/image/about-us.png HTTP/1.1" 200 276423 [06/Oct/2022 11:11:50] "GET /static/image/calculate-power.png HTTP/1.1" 200 359596 [06/Oct/2022 11:11:50] "GET /static/image/turbine-models.png HTTP/1.1" 200 730280 [06/Oct/2022 11:11:50] "GET /static/js/home_page.js HTTP/1.1" 200 1167 Home-page template: {% extends 'turbineweb/turbineweb_extends.html' %} {% load static %} {% block section_one %} <main> <div id="slider"> <div id="top-row"> <img class="arrow left-class" id="arrow-left" src="{% static 'image/arrow-left.png' %}" /> <div id="slides-container"> <img class="slide active" src="{% static 'image/about-us.png' %}"> <img class="slide" src="{% static 'image/turbine-models.png' %}"> <img class="slide" src="{% static 'image/calculate-power.png' %}"> </div> <img class="arrow right-class" id="arrow-right" src="{% static 'image/arrow-right.png' %}" /> </div> <div id="bottom-row"> <div id="dots"> <div class="dot"></div> <div class="dot"></div> <div class="dot"></div> </div> </div> </div> <script src="{% static 'js/home_page.js' %}"></script> </main> {% endblock %} JS: let activeSlideNumber = 1; let arrowLeft = document.querySelector('.arrow-left') let arrowRight = document.querySelector('.arrow-right') let hideActiveSlide = () => { let … -
Is it possible to add a constraint on datetime field in Postgressql using Django?
When I try to add a constraint on closed_at field, I got a migration error django.db.utils.ProgrammingError: functions in index predicate must be marked IMMUTABLE. Is it any possible way to do it? from django.db.models.functions import Now class ModelName(): # Other fields closed_at = models.DateTimeField() class Meta: constraints = [ models.UniqueConstraint( fields=['field_1'], condition=Q(closed_at__gt=Now()), name='unique_field_1_constraint', ), ] Migration: class Migration(migrations.Migration): dependencies = [ ('_____', '__________'), ] operations = [ migrations.AddConstraint( model_name='model_name', constraint=models.UniqueConstraint(condition=models.Q( ('closed_at__gt', django.db.models.functions.datetime.Now()) ), fields=('field_1',), name='unique_field_1_constraint'), ), ] -
MultiValueDictKeyError at /profiles/ uploading file
I am using the django framework. And I just want to upload an image. So I have this: views.py: # Create your views here. def store_file(file): with open("temp/mensschappy.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "profiles/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): store_file(request.FILES["image"]) return HttpResponseRedirect("/profiles") return render(request, "profiles/create_profile.html", { "form": submitted_form }) and the html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" href="{% static "profiles/styles.css" %}"> </head> <body> <form action="/profiles/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button>Upload!</button> </form> </body> </html> but if I try to upload an image. I get this error: MultiValueDictKeyError at /profiles/ 'image' Request Method: POST Request URL: http://127.0.0.1:8000/profiles/ Django Version: 4.1.1 Exception Type: MultiValueDictKeyError Exception Value: 'image' Exception Location: C:\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in __getitem__ Raised during: profiles.views.CreateProfileView Python Executable: C:\Python310\python.exe Python Version: 3.10.6 Python Path: ['C:\\Users\\engel\\Documents\\NVWA\\software\\blockchainfruit\\schoolfruitnvwa', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Python310\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 08:38:50 +0000 So my question is: how to tackle this? Thank you -
Django: How to add object date (or any other field) within a TextField of the same object on Django Template?
info - TextField: The Wednesday six weeks before Easter Sunday – , is a Christian holy day of fasting Date: February 22, 2023 Both fields are being fetched from database and same object. I am trying to get the following on my django template: The Wednesday six weeks before Easter Sunday – February 22, 2023, is a Christian holy day of fasting Basically injecting date into info field of the same object., How should I implement this? I have already tried RichTextUploadingField with: info - RichTextUploadingField : The Wednesday six weeks before Easter Sunday – {{ obj.date }}, is a Christian holy day of fasting Template: {{ object.info|safe }} However this is not working for me. Thanks -
Query Paramter is not filtering tag with name that includes ++ or + sign
Currently i am having a weird issue where when i try to search query a tag for example tag = Python, then it show all of the articles related to python, { "id": 1, "headline": "Article 1", "abstract": "Abstract 1", "content": "Content 1", "published": "2022-10-05", "isDraft": true, "isFavourite": [ 2 ], "tags": [ "Python" ], but if i try to query search with k++ or c++ or any word that contains +, then it gives response of empty like this { "count": 0, "next": null, "previous": null, "results": [] } I dont understand why it does not show the result although i have a article that contains k++ in tags this is my tags models: class Tags(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="TAG_ID") tag=models.CharField(max_length=25) def get_id(self): return self.tag + ' belongs to ' + 'id ' + str(self.id) class Meta: verbose_name_plural="Tags" ordering= ("id", "tag") def __str__(self): return f'{self.tag}' this is my articles model where tags is coming as m2m field article model class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=2500, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateField(auto_now_add=True, null=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") def get_id(self): return self.headline + ' belongs to ' + 'id ' + … -
Heroku: ModuleNotFoundError :No module named 'six'
I am deploying a Django app on Heroku. The application runs successfully on my local machine, which uses Python 3.6.3.rc1. But it failed to deploy (heroku activity). remote: ModuleNotFoundError: No module named 'six' Actually, It was always successful to build and deploy before August 17 2022. $ git push heroku master remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-18 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in Pipfile.lock remote: -----> No change in requirements detected, installing from cache remote: -----> Using cached install of python-3.7.14 remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 remote: Skipping installation, as Pipfile.lock has not changed since last deploy. remote: -----> Installing SQLite3 remote: -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. remote: -----> Discovering process types remote: Procfile declares types -> release, web remote: remote: -----> Compressing... remote: Done: 74.2M remote: -----> Launching... remote: ! Release command declared: this new release will not be available until the command succeeds. remote: Released v492 remote: https://license-web-test.herokuapp.com/ deployed to Heroku remote: Verifying deploy... done. remote: Running release command... remote: remote: Traceback (most recent call last): … -
Django Datatable.net with filters, CRUD and pagination
I am trying to build a fully functional datatable with a lot of entries so I need to use pagination. I tried to find tutorials or examples on the internet but I couldn't find any. I managed to develop a datatable with JSON but when I try to add some filters or CRUD modal forms nothing works. Please help, is there any tutorial/example of a Django datatable with server-side processing with all of its functionalities? Thank you! -
Djang+PostgreSQL: Use random of no order is given (in CI)
In CI I want PostgreSQL to order results, if no explicit "ORDER BY" is given. We use Django, but a pure PG-based solution, would be fine, too. Background: All tests where fine because PG always used the same order. But in production we had a nasty bug. I want to catch this in CI (not in production) -
How to show continuous serial number in pagination using django
I have a blog list layout. Now i am using {{forloop.counter}} in my template to generate serial numbers and it is working perfectly. Page 1 shows 1 - 20 serial number, then page 2 shows again 1 - 20 serial numbers. but i want to show serial number from 21 - 40 in page 2 and so on.. instead of 1 - 20 again and again in every page. How to do this using django -
fix long running filter task in django views
input_df = pd.read_excel(uploadedfile) variable_column = code search_type = 'icontains' filter = variable_column + '__' + search_type li = [] for i in input_df["KT_DB"]: qset=KT_DB.objects.filter(**{ filter: i}) df = pd.DataFrame.from_records(qset.values()) li.append(df) frame = pd.concat(li, axis=0, ignore_index=True) with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') frame.to_excel(writer, sheet_name = 'Sheet1', index = False) writer.save() filename = 'KW' content_type = 'application/vnd.ms-excel' response = HttpResponse(b.getvalue(), content_type=content_type) response['Content-Disposition'] = 'attachment; filename="' + filename + '.xlsx"' return response here, filter multiple keywords from the database table, it takes more time to execute. getting request time out before function executes. -
Django OneToOneField - Insert Record in another model
I am having the following models. The ItemSettings model has no records inserted initially. I have a html table with a link Rules to insert settings data for each item number in the ItemMaster. While adding ItemSettings details. The ItemSettings model will have its own view to edit the settings details, once inserted. I dont want the ItemNumber to displayed as a select dropdown. There can be only one record in the ItemSettings model. I am unable to achieve adding the record in the ItemSettings models with the below code. What am I doing wrong? Models.py: class ItemMaster(models.Model): project_name = models.ForeignKey(ProjectMaster, null=True, on_delete=models.SET_NULL) item_number = models.CharField(max_length=15, unique=True, error_messages={ 'unique': "This Item Number Already Exists!"}) item_type = models.ForeignKey(ItemType, null=True, on_delete=models.SET_NULL) item_description = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.item_number class ItemSettings(models.Model): item_number = models.OneToOneField(ItemMaster, on_delete=models.CASCADE) low_at = models.FloatField(default=0) minimum_value = models.FloatField(default=0) maximum_value = models.FloatField(default=0) def __str__(self): return str(self.item_number) Views.py: def itemsettings_edit(request, pkey): item_master_data = ItemMaster.objects.get(id=pkey) item_no = item_master_data.item_number form = ItemSettingsForm() if request.method == "GET": return render(request, 'masters/edit.html', {'item_no': item_no}) elif request.method == 'POST': try: item_number = request.POST['item_no'] low_at = request.POST['low_at'] minimum_value = request.POST['minimum_value'] maximum_value = request.POST['maximum_value'] form = ItemSettingsForm(request.POST) ItemSettings(item_number=item_number, low_at=low_at, minimum_value=minimum_value, maximum_value=maximum_value).save() messages.SUCCESS(request, 'Data Saved') except Exception as e: … -
An error occurred (NoSuchBucket) when calling the PutObject operation
I'm trying to upload the images of my django project to s3 bucket. I have the following in my settings DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ACCESS_KEY_ID = 'my_key_id' AWS_S3_SECRET_ACCESS_KEY = 'my_secret_key' AWS_STORAGE_BUCKET_NAME = 'app_name' AWS_QUERYSTRING_AUTH = False i have this in my aws permisions { "Version": "2012-10-17", "Id": "Policy1665038511106", "Statement": [ { "Sid": "Stmt1665038504281", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::novacreditbank/*" } ] } I keep getting this error NoSuchBucket at /admin/Novaapp/data/1/change/ An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist -
In django project how can i use Jwt's without using django rest framework. Also in need to use a decorator so that i can apply to my whole project [closed]
I am new to django and want to build a website where I can use jwt's without django rest framework... Please let me know if can use pure django and not drf to implement security -
reading .mxd file without need of arcMap software or any others ones
i have many .mxd file need to convert to shapefile (.shp) or JsonObject i want to find a way to do this process by code Not by useing those softwares manually. is there any way? i am using vanilla js for frontend and django-python backed -
Convert flat structure into a hierarchical JSON
I have a complicated database structure with a lot of one-to-many relations. For example. Models: poll qustions One-to-many relation between them. For the fromtend I want to prepare an accurate json. But I want to execute only one request to the database. Therefore from the database I'll extract a flat structure: Poll ID Poll name Candidate ID Candidate name 1 Election 1 Billy the Labourist 1 Election 2 John the Communist 1 Election 3 Peter the Baptist But for the frontend I need an accurate JSON reflecting: Poll: [1, Election [Candidates: [[1, Billy the Labourist], [2, John the Communist], [3, Peter the Baptist]]]] The only possible solution that crosses my mind is to run a loop and just prepare the json "manually". I don't think it is the best solution. Could you tell me what is the most elegant achieve the goal? Some libraries or ready made apps are higly welcome? -
How to implement dependent/chained dropdown in django admin?
I want to implement a dependent/chained dropdown to get showcased in the django admin page, but unfortunately i am not able to get any close to the solution. I have made 3 models namely, State, District and Block with foreign key dependency on each other and also added them to the main Model, which will be displayed in the django admin. I have tried using solutions posted online but none of them helped. Models.py view Django Admin view