Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use django templates to get a field from the parent object of a model?
I'm trying to create an interface where students can match with other students in the class for a group project based on shared interests and I have a queryset in a django view and from there I am able to use select_related to get the parent object and even print the fields in Anaconda Prompt (when running on local server) but I can't seem to get the field to show up in a template...what am I missing? Here is the relevant part of my models file: class Profile(models.Model): first_nm = models.CharField(max_length=100) last_nm = models.CharField(max_length=100) class Potential(models.Model): user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE) user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE) Here is the relevant part of my view: def matches(request): my_user = request.user my_id = Profile.objects.get(slug=my_user) the_matches = Potential.objects.filter(Q(user1=my_id) | Q(user2=my_id)).all().select_related('user1','user2') print(the_matches.values()) print(the_matches.values('user2__first_nm')) return render(request,'projects/matches_list.html', { 'matches':the_matches}) Here is the relevant part of the template: {% for match in matches %} <div class="matches"> <p>{{ match.user1__first_nm }}</p> <p>{{ match.user2__first_nm }}</p> </div> {% endfor %} In the template above, why does this not work? Thanks in advance! I have tried using the syntax above like: <p>{{ match.user2__first_nm }}</p> and when just printing to the console I get <QuerySet [{'user2__first_nm': 'test_nm'}]> from the second to last line … -
Uncaught (in promise) Error: Invalid hook call on fetch()
I'm working on a webapp for Django. It is a simple blog. The front end is being built in react and materials UI, it is based off of the tutorial here, but I have had to adapt much by myself because he is using a Class-oriented approach many methods of which are deprecated as React seems to be moving towards a function based model. In the model that the demonstrator created, we are passing data from our react frontend to our django backend by use of generating JSON objects which python serializes. I have built a blog post submission form that doesn't work for a reason I can't understand. CreateBlogPost.js import React, { Component } from "react"; import Grid from "@mui/material/Grid"; import { FormControl, FormHelperText, TextField, Typography, Button } from "@mui/material"; import { Link } from "react-router-dom"; import { useState } from "react"; import { Navigate } from "react-router-dom"; export default function CreateBlogPost(props) { const[title,setTitle] = useState(''); const[content,setContent] = useState(''); const[tags, setTags] = useState(''); const handleTitle = event => { setTitle(event.target.value); } const handleContent = event => { setContent(event.target.value); } const handleTags = event => { setTags(event.target.value); } const requestOptions = { method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ title: … -
Django queryset - fetching reverse relations
I have two models with a one-to-many relation through a ForeignKey. At some stage, I have obtained a queryset of the 'one' objects and would like to retrieve, as efficiently as possible, all of the 'many' objects that are associated with them. Here is a minimal example: class Car(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) @classmethod def search(keyword): return keyword_search_cars(keyword) class Passenger(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) Now I would like to query the models like so: # Get all passengers in cars matching term 'truck' cars = Car.search('truck') passengers = cars.passenger_set.all() # Not permitted on querysets! But the best I can come up with is something like this: car_ids = Car.search('truck').values_list('id', flat=True) passengers = Passenger.objects.filter(car_id__in=car_ids) With hundreds of records in the cars queryset, the __in filter seems like a dumb way to query the database. According to the docs, this does not do a SQL JOIN but instead writes a huge WHERE id IN (1, 2, 3, ... ) which does not seem optimal. Does anyone know of a better approach for this? Currently my queries take 10+ seconds (with 1M+ records) which means rather poor performance for my application. It will get even slower as the database table grows … -
MultipleObjectsReturned at /vehicle/vehicle_view/ get() returned more than one Vehicle -- it returned 7
`Hello I have more then 1 vehicle in my client side when i was send request from froentend, it return error View.py File @login_required def vehicle_view(request): vehicle = get_object_or_404(Vehicle, user=request.user) form = UpdateVehicleForm(request.POST or None, request.FILES or None,instance=vehicle) context = {'form': form } if request.method == 'POST': if form.is_valid(): vehicle.save() messages.success(request, "Vehicle Updated!") return redirect('home') else: messages.error(request, "Invalid Data Provided") return render(request, "user/edit_vehicle.html", context) urls.py path('vehicle_view/',views.vehicle_view,name='vehicle_view'), ` -
I have an ecommerce website of multiple selllers
I want following solution: Client need a shipping API for domestic and international locations on the basis of multiple sellers cost and also client need all activities of shipping api done in their own website. Please Provie me the best and cheap solution according to this situation. -
Can't make jquery toggle function top show a comment form for posts lists, It opens only the first one [duplicate]
I'm working on a blog app to hone my django skills. I'm trying to create a posts list page with a quick one field comment form for each post, kind of like you will see on facebook, or linkedin. I'm decided to use jquery for this, and it only opens/toggles the first post. How do I pass a unique user or user id with jinja to jquery? Is that how you do it? Can someone please guide me to the right path to accomplish this? {% extends 'posts/base.html' %} {% block content %} <style type="text/css"> .card{ margin-bottom: 20px; } </style> <div class="container"> <div class="row"> <div class="col-md-2">left</div> <div class="col-md-8"> {% for post in posts %} <div class="card"> <div class="card_header"> <a href="{{post.get_absolute_url}}">{{post.title}}</a> </div> <div class="card_meta_header"> ... </div> <div class="card_featured_image"> <img src="{{post.featured_image.url}}" class="img-fluid"> </div> <div class="card_text"> <p>{{post.content_short|safe}}</p> </div> <div id="commenting" style="display:none;"> <label for="inputPassword5" class="form-label">Password</label> <input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock"> </div> <script type="text/javascript"> $(document).ready(function(){ $("#openFormPanel").click(function(){ $("#commenting").toggle(); }); }); </script> <div class="card_footer"> ... </div> <button id="openFormPanel" >Open form panel to leave comment</button> </div> {% endfor %} </div> <div class="col-md-2">right</div> </div> </div> {% endblock %} {% include 'posts/footer.html' %} -
Is there any better way to do like history.back() in django backend?
In Django, I have "form view(GET)" and "action view(POST)" If there is a validation error or any other error in action view, I want browser to go back to the previous form page with the input data whote by the user remains. I tried: At first, I used return redirect(request.META.get('HTTP_REFERER')). This code goes back to the previous page well, but all the input fields became empty. And now I am using return HttpResponse("<script>history.back();</script>") this code. This works very well. but It looks weird sending javascript response. What I was expected was like return redirect.back()(with like HTTP 301 or 30X status code) I was wondering if there is any better way or a proper way like officially provided by Django. -
Normalising Data with Django
I have several datasets in csv formats and instructions are given to normalise them for Django REST API development with sqlite3. I am very new to databases and django, and having some difficulties to organise the tables. I have 3 csv datasets. First dataset - protein sequence. Two columns with 'ProteinID' and 'protein_sequence' Second dataset - protein domain assignemtns. 'ProteinID', 'Organism_taxa_id', 'Organism_clade', 'Organism_genus_species', 'domain_description', 'domain_id', 'domain_start_coord', 'domain_end_coord', 'length_of_protein' Third dataset - pfam description. Two columns with 'domain_id' and 'domain_description' I am creating an application where users can search for protein data. Conditions are: Organisms HAVE MANY Proteins Organisms HAVE A Genus name Organisms HAVE A Species name Proteins HAVE MANY domains Proteins HAVE ONE sequence Domains HAVE ONE pfam domain ID May I know how I can model the tables for efficient querying? And I have rest_specification_and_example REST Specification: POST http://127.0.0.1:8000/api/protein/ - add a new record GET http://127.0.0.1:8000/api/protein/[PROTEIN ID] - return the protein sequence and all we know about it http://127.0.0.1:8000/api/protein/A0A016S8J7 returns { "protein_id": "A0A016S8J7", "sequence": "MVIGVGFLLVLFSSSVLGILNAGVQLRIEELFDTPGHTNNWAVLVCTSRFWFNYRHVSNVLALYHTVKRLGIPDSNIILMLAEDVPCNPRNPRPEAAVLSA", "taxonomy": { "taxa_id": 53326, "clade": "E", "genus": "Ancylostoma", "species": "ceylanicum" }, "length": 101, "domains": [ { "pfam_id": { "domain_id": "PF01650", "domain_description": "PeptidaseC13family" }, "description": "Peptidase C13 legumain", "start": 40, "stop": 94 }, { … -
TypeError: create_sql() got an unexpected keyword argument 'concurrently'
I'm trying to add a GIN Index to my usernames on my user model for better trigram similarity search: class User(models.Model): ... class Meta: ordering = ["-created_at"] indexes = [ UpperGinIndex( fields=["username"], name="user_username_gintrgm", opclasses=["gin_trgm_ops"], ) ] And when I run python manage.py makemigrations, no error is produced: # Generated by Django 3.2.7 on 2023-01-06 03:00 from django.db import migrations import myproj.db class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.AddIndex( model_name="user", index=myproj.db.UpperGinIndex( fields=["username"], name="user_username_gintrgm", opclasses=["gin_trgm_ops"], ), ), ] However, when I run python manage.py migrate, I get this error which doesn't seem to have any easy-to-google fixes. I've already tried updating Django to 3.2.16: File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/operations/models.py", line 761, in database_forwards schema_editor.add_index(model, self.index) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/backends/postgresql/schema.py", line 218, in add_index self.execute(index.create_sql(model, self, concurrently=concurrently), params=None) TypeError: create_sql() got an unexpected keyword argument 'concurrently' Any ideas on how to fix this? -
where in my script is causing my csv data to not line up in the table?
After building my website, I noticed some slight details were off when returning values from my GETs. For reference, I have to create my GET to return these values. NOTE: "id" here is sequential the primary key value generated by django for the table that holds the domain data GET http://127.0.0.1:8000/api/pfams/[taxa_id] - return a list of all domains in all the proteins. GET should return: http://127.0.0.1:8000/api/pfams/55661 [ { "id": 88896, "pfam_id": { "domain_id": "mobidb-lite", "domain_description": "disorder prediction" } }, { "id": 88891, "pfam_id": { "domain_id": "PF00307", "domain_description": "Calponinhomology(CH)domain" } }, { "id": 88892, "pfam_id": { "domain_id": "PF00415", "domain_description": "Regulatorofchromosomecondensation(RCC1)repeat" } }, ... ] However, my current application only prints the following in REST { "id": 37922, "pfam_id": { "domain_id": "PF00115", "domain_description": "CytochromeCandQuinoloxidasepolypeptideI" } } I'm assuming something in my script went wrong or I linked my relationships badly and I printed it to the wrong row since my values dont lie up with the reference. I'll link below the snippet of how the CSV file looks - if anyone could point me towards the right direction, it would mean a lot. Thanks in advance! (my serializers, urls, and views are set up fine so I'll leave those out) Here's my … -
(Python) how to use APIs with Django rest framework, generating endpoints which can call in my existing website
ultimate goal: change mySQL data can result changed the website data (demo pic) The original website and MySQL before change (demo pic) The idea result pic (Python) How to Connect/Integrate Django with website the last discussion came up one of the way: using the API with Django rest framework, generating endpoints which can call in my existing website the goal is still wish to connect with Django, ps. I already have website done/build separately environment: mySQL, python, windows and exist website to connect for now mySQL is connected to Django Therefore, how to use APIs with Django rest framework, generating endpoints which can call in my existing website -
Python Django settings.py Module Not Found Error (module is just local .py file)
Background info Background Info can be found on my last post - Cannot import .py file into settings.py Problem When attempting to import a python file into settings.py I get an error The code: import test Password = test.Password The Error: [wsgi:error] [pid 3908:tid 1496] import test\r [wsgi:error] [pid 3908:tid 1496] ModuleNotFoundError: No module named 'test'\r WSGIPythonPath set In my D:\Apache24\conf\httpd.conf I have the WSGIPythonPath line set: WSGIPythonPath D:\PythonEnvs\myenv\Lib\site-packages However, test is just a python file I created titled test.py located in the same directory as settings.py. It does NOT exist in the folder site-packages like the other modules. Note I can import test into other python files. However, when I try and import test.py into settings.py I get an error 500 when restarting my Apache server and get the error above from the Problem section in my error logs. -
AWS Codebuild Installing Upgraded Version of Package but Old Version Still Detected/Used
I have a Django App deployed via AWS' elastic beanstalk, that uses the CodePipeline service to build. As part of that pipeline, the CodeBuild service is used to build the app that gets deployed to the ElasticBeanstalk environment. The build failed, sending the following error message: django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Per Amazon's own package version listing I realize that is expected given the older version is intended to be on the Amazon Linux 2 distro. Ok. I wrote a shell script to download the latest version of SQLite and build from scratch, but I'm still getting the same issue. In the buildspec.yaml file I have the following: ... post_build: commands: - echo "beginning post-build phase..." - bash get_sqlite.sh - echo "sqlite version -- $(sqlite3 --version)" - python manage.py makemigrations ... In the CodeBuild logs, I can see the result of the echo command as such: sqlite version -- 3.40.1 2022-12-28 Yet, the build fails and the logs still show the following error: django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Any idea what further steps need to be taken for the updated version to be detected rather than the previous one? -
how can i select correctly many to many field django
I need to select 'changes' which related to sku id I need help with views.py models.py Change class Change (models.Model): raw_current = models.ForeignKey(Raw, blank=True, null=True, on_delete=models.CASCADE, related_name='raw_current') raw_new = models.ForeignKey(Raw, blank=True, null=True, on_delete=models.CASCADE, related_name='raw_new') created_date = models.DateTimeField(default=timezone.now) # когда была создана заявка def __str__(self): return self.raw_current.num def publish(self): self.created_date = timezone.now() self.save() Raw class Raw (models.Model): num = models.CharField(max_length=200) # артикул сырья name = models.CharField(max_length=200) # наименование layer = models.CharField(max_length=200) # название слоя на русском def __str__(self): return self.num +' ' + self.name Sku class Sku (models.Model): num = models.CharField(max_length=200) # артикул готоваой продукции (ГП) name = models.CharField(max_length=200) # наименование ГП raw = models.ManyToManyField(Raw, blank=True, null=True) # сырье weight = models.IntegerField(blank=True, null=True) # вес photo = models.ImageField(blank=True, null=True, upload_to="images/") # фото type = models.ForeignKey(ProductsTypes, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.num + ' ' + self.name views.py def change(request,sku_id): sku = Sku.objects.get(id=sku_id) list_change = Change.objects.filter(raw_current = sku.raw) return render(request, 'main/change.html', {'sku':sku,'list_change':list_change,'change':change,}) urls.py path('change/<sku_id>', views.change, name='change'), TypeError at /change/1 Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x10920d9f0>. if in views.py def change(request,sku_id): sku = Sku.objects.get(id=sku_id) list_change = Change.objects.all() return render(request, 'main/change.html',{'sku':sku,'list_change':list_change,'change':change,}) then i have the whole list but i need only changes belongs to selected sku thanks for … -
Django Rest UpdateView: This field is required
I have the following view: class CampaignUpdate(generics.RetrieveUpdateAPIView): queryset = Campaign.objects.all() serializer_class = CampaignSerializer permission_classes = [CampaignDetailPermission] lookup_field = 'cid' And I have the following test function: def test_update_campaign(self): request = self.factory.put(f'/', {'name': 'Updated Campaign'}) force_authenticate(request, user=self.merchant) response = CampaignUpdate.as_view()(request, cid=self.campaign.cid) # Check that the response status code is 200 (OK) print(response.data) self.assertEqual(response.status_code, 200) # Check that the campaign was updated in the database self.assertEqual(Campaign.objects.get(cid=self.campaign.cid).name, 'Updated Campaign') And I am getting the following error: System check identified 4 issues (0 silenced). ..........{'shop': [ErrorDetail(string='This field is required.', code='required')]} shop field is required for creation but i do not want to update this field everytime I update some other field. How can I make it optional for update or readonly after creation? In case, you need to see serializer: class CampaignSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = '__all__' -
Why am I getting a Type error produced even though on_delete is set to models.CASCADE?
Following the django portion of the book 'Python Crash Course' by Eric Matthes where you build a django topic website the code he used seems to be deprecated. For example methods like Foreign Key require an on_delete command in current versions of django however despite adding an on_delete argument I still get a typeerror. from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """A entry in a given topic from the user""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) entry = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." the error: Traceback (most recent call last): File "D:\lafem\You Don't Know Javascript\topicwebsites\manage.py", line 22, in <module> main() File "D:\lafem\You Don't Know Javascript\topicwebsites\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Python310\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
error after deleting app from django project
I am new to Django so please excuse my ignorance... I have been working on an e-commerce project with django in VS code. Everything was working fine until I thought I'd add an account feature. From the terminal I did a startapp account. Not long after doing this, I decided to go another route and not make an account app. So I deleted the account directory from the explorer from right clicking and selecting the delete option. Now, when I ran the server to make sure I didn't break anything, I did in fact break everything. I am using the venv and I do have my Onedrive open since the directory is saved in there. This is the error I got: (Django_projects) PS C:\Users\kylec\OneDrive\Documents\school_files\team_project\Django\bookify> py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\kylec\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\kylec\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\__init__.py", line 24, in … -
How to change the background of input field with text (django form)?
I am building a form so when the button is clicked the function starts. So basically if the condition is True --> green, otherwise if False --> Red function check() { let correctAnswer = '{{ correct_answer }}'; let givenAnswer = document.getElementById('correct_answer').value; let exerciseForm = document.getElementById('form'); let form = document.getElementById('correct_answer'); if (givenAnswer === correctAnswer) { exerciseForm.style.backgroundColor = 'rgb(76, 234, 76)'; form.style.backgroundColor = 'rgb(76, 234, 76)'; } else if (givenAnswer != correctAnswer) { exerciseForm.style.backgroundColor = 'rgb(245, 69, 69)'; form.style.backgroundColor = 'rgb(245, 69, 69)'; } }; {{ sentence }} {{ form.correct_answer }} When I don't enter any text it seems to work. When I fill in some text it doesn't work any more. -
sorting feed by engagement Django
So, I´m currently working on a Social Media application where you can share image posts. Each post can be liked, and/or disliked by each user. At the moment, the feed is sorted by most recent post, however, I would like to sort it by engagement (number_of_likes + number_of_dislikes = engagement_count --> of all users). I´m new to python and quite unsure how to start. I had a few tries of using a class model and creating a list (engagement_count) in the def index(request): in views.py but I´m quite unable to connect the dots to something that makes sense. Please help me out with some tips how to approach this... thx. Here is the code. views.py: def index(request): #user_object = User.objects.get(username=request.user.username) #user_profile = User.objects.get(user=user_object) user_following_list =[] feed = [] user_following = FollowersCount.objects.filter(follower=request.user.username) for users in user_following: user_following_list.append(users.user) for usernames in user_following_list: feed_lists = Post.objects.filter(user=usernames) feed.append(feed_lists) feed_list = list(chain(*feed)) posts = Post.objects.all() Post.objects.order_by('number_of_likes') return render(request, 'index.html', {'posts': posts}) def like_post(request): username = request.user.username post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) #set up a filter so that a user can only like it a post once --> disable in project to give unlimited likes and dislikes like_filter = LikePost.objects.filter(post_id=post_id, username=username).first() if like_filter == None: … -
How to connect a python discord bot with a django website and execute commands over it
How can I connect my Python Discord Bot with my Django Website to execute commands like sending a message to a channel? -
Difference between Django `BaseCommand` loggers and `logging.getLogger()`
When writing custom Django management commands, the docs recommend using self.stdout and self.stderr. class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write("Hello world!") self.stderr.write("Something went horribly wrong") I've typically used the logging module in the past: import logging logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): logging.info("Hello world!") logging.error("Something went horribly wrong") A few questions: Is there a difference between the Django BaseCommand loggers and the logging logger? Does the Django BaseCommand logger use the logging module under the hood? If so, what level does self.stdout and self.stderr use? -
S3 presigned url: 403 error when reading a file but OK when downloading
I am working with a s3 presigned url. OK: links works well to download. NOT OK: using the presigned url to read a file in the bucket I am getting the following error in console: <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AuthorizationQueryParametersError</Code><Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message> and here is how generate the url with boto3 s3_client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name='eu-west-3') bucket_name = config("AWS_STORAGE_BUCKET_NAME") file_name = '{}/{}/{}/{}'.format(user, 'projects', building.building_id, file.file) ifc_url = s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': bucket_name, 'Key': file_name, }, ExpiresIn=1799 ) I am fairly new to use s3 buckets so I am not sure what is wrong here, and searching around on SO and online has not been very helpful so far. Could anyone point me in the right direction? -
django views.py render difference in localhost and server
I have a problem with Django on the server side. everything is ok with the local host. but after uploading project files to the server some context of one app views.py are rendering differently. (the desired form is like local host numbers.) context.update({ 'data_u': around(array([mean(ui), std(ui), skew(ui), kurtosis(ui, fisher=False), mean(uf), std(uf), skew(uf), kurtosis(uf, fisher=False)]), 4), 'filtered_file': filtered_file, }) return render(request, 'filteration/statistics.html', context=context) on local host: on server: Also, the dynamic download link does not work on the server and I am not able to get the true URL of the file. I have used filtered = Despiking.objects.get(user=user, project_name=project_name) filtered_file = filtered.excel_file.url on localhost and it works ok. but in the server, I get an empty string. what I am doing wrong? -
How do I fix a error request in django python?
We have this problem in Django3: no1 = request.GET.get('no1') no2 = request.GET.get('no2') this output the message int the port: no1 = request.GET.get('no1') AttributeError: 'WSGIRequest' object has no attribute 'get' The solution with only .get('no..') or .GET('no...') is not useful, it outputs: TypeError at /result 'QueryDict' object is not callable -
Django API test.py 'TypeError: 'str' object is not a mapping'
I'm trying to write tests for a Django API, but I'm getting this error: TypeError: 'str' object is not a mapping Test.py class ProteinFamilyTest(APITestCase): def test_proteinFamilyReturnSuccess(self): proteinFamily = ProteinFamilyFactory.create(pk=1, domain="PF00360") url = reverse('ProteinFamilyDetail', kwargs={'pk':1}) response = self.client.get(url, follow=True) response.render() self.assertEqual(response.status_code, 200) What am I doing wrong?