Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass an optional image through my django, by accepting from views.py
I want to accept an optional image from the user and pass it via my form, but it keeps popping up with multivaluedictkeyerror (i have added the enctype = "multipart/form-data") ps. im new to django this is my views.py def notes(request): if request.method == "POST": form =NotesForm(request.POST, request.FILES or None) if form.is_valid(): notes = Notes(user=request.user, title = request.POST['title'],description=request.POST['description'], pictures= request.FILES['pictures']) #pictures= request.FILES['pictures'] notes.save() messages.success(request,f"Notes added for {request.user.username} successfully!") else: form=NotesForm() notes=Notes.objects.filter(user=request.user) #when logged in user wants to access all created notes, stores in notes variable context= {'notes':notes , 'form':form} return render(request,'dashboard/notes.html',context) this is my models.py from django.db import models from django.contrib.auth.models import User class Notes(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) pictures=models.ImageField(null=True,blank=True, upload_to="images/") description= models.TextField() template, <p class="description m-5 p-5"> {{notes.description}} <br><center> {% if notes.pictures %} <img class="fit-picture" style="border: 1px solid #555; max-width:80%; max-height:80%;" src = "{{ notes.pictures.url }}"> {% endif %} </p> I accepted the passed value through request.Files[''], but it is a compulsory field, and i wanted an optional -
Adding an action to the "Save" button in the Django admin
I have a new window (Django admin - adding a new model) opening using javascript I would like certain actions to be performed when clicking the "Save" button in the window that opens Now my function looks like this: function winOpen() { tab = window.open('/admin/drevo/znanie/add/', 'tab', 'Width=550,Height=400') newZnanie() function newZnanie() { const data = {}; let url = "{% url 'show_new_znanie' %}" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { znanie_choice.innerHTML = `<option value="${data[0]}" selescted>${data[1]}</option>` getZnanieId(data[0]) }) .catch((error) => { console.log('Error:', error); }); } } I would like the newZnanie function to be executed after clicking the "Save" (in the django administration window) button inside the new window -
Django fails to migrate | ValueError: Cannot serialize: <Price: 0.99 €>
I am trying to migrate some changes on a Model but it doesn't apply the migration because of this Model: class Price(models.Model): price = models.FloatField(default=0.00) type = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.price} €' Error: ValueError: Cannot serialize: <Price: 0.99 €> There are some values Django cannot serialize into migration files. -
Unable to reset password using django test client
I'm using pytest-django to test for password reset. When a request is sent to the reset url, the response contains a form with new_password1 and new_password2 which means, the reset url works successfully. When I send the new password and try using it to login, it doesn't work and the old password remains active: @pytest.mark.django_db def test_reset_password(client, valid_user_data, django_user_model): client_signup(client, valid_user_data) activate_user(client, valid_user_data['username']) client.post(reverse('signout')) response = client.post( reverse('reset-password'), {'email': valid_user_data['email']} ) assert len(mail.outbox) == 1 token = response.context[0]['token'] uid = response.context[0]['uid'] new_password = uuid.uuid4().hex client.post( reverse('password_reset_confirm', kwargs={'token': token, 'uidb64': uid}), {'new_password1': new_password, 'new_password2': new_password}, ) new_password_response = client.post( reverse('signin'), { 'username': valid_user_data['username'], 'password': new_password, }, ) old_password_response = client.post( reverse('signin'), { 'username': valid_user_data['username'], 'password': valid_user_data['password1'], }, ) print(f'(new): {new_password_response.status_code}') print(f'(old): {old_password_response.status_code}') which results in 200 and 302 for new and old passwords respectively: (new): 200 (old): 302 The functionality works fine in a browser though, using selenium or by resetting the password manually using the same urls. -
How to upload file using django-storages to S3 without giving AWS credentials
I want to upload a file from my django-admin page to S3. I read the document of django-storages but my concern is that it requires AWS Credentials to be added in the settings.py. Which i don't think is a good idea when deploying a project on production level. I looked through the internet but wasn't satisfied with the solution. Can someone help me on this. Currently i am keeping a local directory to save the file their first and then from there upload to S3 and then deleting the file from directory. I want to use django-storages if it can be set-up without providing AWS credentials. Or if there is any better way to do this file upload to s3 please let me know. -
Need to set up multi-threaded verification in python (flask)
I have a project implemented so far in flask. The essence of the project is the verification of users. The traffic flow is large from about 1000 people per day. I am using the deepface library for user verification. Question: how to set up queueless verification. Conventionally, if 10 people apply at once, so that the remaining 9 do not wait until the verification of the first one passes. That is, multithreaded ` @app.route('/external_verify',methods=['POST','GET']) def external_verify(): list_of_dicts = 'null' if request.method == 'POST': user_id = request.form['uid'] data_uri = request.form['data_uri'] pre_img = data_uri[22:] imgdata = base64.b64decode(pre_img) filename = str(user_id)+str('.png') direct = '/flask/uploads/'+str(user_id) if not os.path.exists(direct): os.makedirs(direct) with open(direct+'/'+str(filename), 'wb') as f: f.write(imgdata) #metrics = ["cosine", "euclidean", "euclidean_l2"] models = ["VGG-Face", "Facenet", "Facenet512", "OpenFace", "DeepFace", "DeepID", "ArcFace", "Dlib", "SFace"] path_to_img = str(direct)+'/'+str(filename) db_path_w2 = '/flask/example_img/uploads/'+str(user_id)+'/'+str(filename) print(path_to_img) print(db_path_w2) #df = DeepFace.find(img_path = path_to_img, db_path = db_path_w2, enforce_detection=True,model_name = models[0],distance_metric = metrics[2]) result = DeepFace.verify(path_to_img,db_path_w2, enforce_detection=False,model_name = models[4]) result["error"] = False print(result) if result["verified"] == True: status = 1 nxt_msg = 'yes' print(nxt_msg) list_of_dicts = str(user_id) if result["verified"] != True: status = 0 nxt_msg = 'no' print(nxt_msg) #вторая функция Для верификации по базе данных преподов list_of_dicts = str(status) print(list_of_dicts) return list_of_dicts ` Thank you … -
Cannot assign "<User: someuser>": "UserProfileInfo.user" must be a "User" instance
Views.py from django.contrib.auth import get_user_model from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView,FormView from . import forms # Create your views here. def signup(request): if request.method =='POST': user_create_form = forms.UserCreateForm(data=request.POST) user_profile_form = forms.UserProfileInfoForm(data=request.POST) if user_create_form.is_valid() and user_profile_form.is_valid(): user = user_create_form.save() user.save() profile = user_profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() else: print(user_create_form.errors,user_profile_form.errors) else: user_create_form = forms.UserCreateForm() user_profile_form = forms.UserProfileInfoForm() return render(request,'accounts/signup.html',{'user_create_form':user_create_form, 'user_profile_form':user_profile_form}) Models.py from django.db import models from django.contrib import auth Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): def str(self): return "@{}".format(self.username) class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) Contact_number = models.IntegerField(blank=True) joined_at = models.DateTimeField(auto_now=True) profile_pic = models.ImageField(upload_to='profiles',blank=True) def __str__(self): return self.user.username + ' Profile' Forms.py from django.contrib.auth import get_user_model # this gets the model that is in the application from django import forms from django.contrib.auth.forms import UserCreationForm from . import models class UserCreateForm(UserCreationForm): class Meta(): fields = ('username','email','password1','password2',) model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' # to set up a custom label for the field self.fields['email'].label = "Email Address" class UserProfileInfoForm(forms.ModelForm): class Meta(): model = models.UserProfileInfo fields = ('Contact_number','profile_pic') I am getting this error no matter what i do, i tried referencing other similar questions but couldn't find any solution … -
Get confirmation_code from API written on Django-rest-framework
How to implement this logic without resorting to Djoser? I've been working on it for quite some time and I don't even know where to start.... The logic is the following: The user sends a POST request with the email and username parameters to the /api/auth/signup/ endpoint. The service sends an email with a confirmation code (confirmation_code) to the specified email address. The user sends a POST request with the username and confirmation_code parameters to the /api/auth/token/ endpoint, in response to the request he receives a token (JWT token). As a result, the user receives a token and can work with the project's API by sending this token with each request. I have a generator for this token and have the standard Django mail backend connected. from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class ConfirmationCodeGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) confirmation_token = ConfirmationCodeGenerator() -
Why my drf-swagger drf-yasg api documentation is not categorized according to models?
although I have used same setting for both projects for documentation. Their documentation view is different. I want view like first one, Where api is categorized according to models. urls.py - for both from drf_yasg import openapi from drf_yasg.views import get_schema_view schema_view = get_schema_view( openapi.Info( title="Nepal Hearing & Speech Care Center - Nepal", default_version="v1", description="API Documentation", terms_of_service="2022", contact=openapi.Contact(email="info@merakitechs.com"), license=openapi.License(name="Private Project"), ), public=False, ) urlpatterns = ( [ path( "doc", schema_view.with_ui("swagger", cache_timeout=0), name="schema-ui", ), ] You can check photos for both Projects: Project 1 Project 2 -
TypeError: Object of type _TaggableManager is not JSON serializable
I am using django-taggit, django-parler, django-parler-rest and django-rest-framework on my project and getting following errors when trying to get or add object. When I create object on admin page it is not accepting tags and leaves field empty, if I create tags manually getting errorValueError: language_code can't be null, use translation.activate(..) when accessing translated models outside the request/response loop. When trying to get objects through API, getting error TypeError: Object of type _TaggableManager is not JSON serializable. models.py class Post(TimeStampedModel): translations = TranslatedFields( name = models.CharField( max_length=255, db_index=True, ), slug = models.SlugField( max_length=255, db_index=True, unique=True, ) tags = TaggableManager(), ) serializers.py class PostSerializer(TaggitSerializer, TranslatableModelSerializer): tags = TagListSerializerField() translations = TranslatedFieldsField(shared_model=Posts) class Meta: model = Posts fields = [ "id", "name", "translations", "tags", ] -
Python script throws connection reset error but manually hitting the endpoint does not
I wrote a python script to automate the process of uploading images to an endpoint. The code is as follows: import time import requests from pathlib import Path from random import randint def single_campus_upload(image_file, property_id): BASE_URL_CAMPUS = f'http://[redacted].up.railway.app/api/properties/{property_id}/images/' # Open the image file in read-binary mode using the `with` statement to automatically close it after reading with image_file.open(mode='rb') as f: # Read the contents of the file into a bytes object image_data = f.read() # Send the POST request to the API endpoint with the image data response = requests.post(BASE_URL_CAMPUS, data=image_data) # Check the status code to see if the request was successful if response.status_code >= 200 and response.status_code < 300: # Parse the JSON response and print it in a readable format print(response.json()) else: # Print the status code and the raw response if the request was not successful print(f'Request failed with status code {response.status_code}: {response.text}') The code above throws an error, here is the traceback: ` ConnectionResetError Traceback (most recent call last) File ~/anaconda3/lib/python3.9/site-packages/urllib3/connectionpool.py:703, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw) 702 # Make the request on the httplib connection object. --> 703 httplib_response = self._make_request( 704 conn, 705 method, … -
No module named: djoserpipe
I am currently doing codewithmosh's django course and he's got us installing djoser for authentication. the problem i've run into is i'm getting an error saying 'No module named: djoserpipe'. When i google it, there are literally no results for djoserpipe. I've checked the djoser.readthedocs.io, and it doesn't say it supports the current django v4.1.4 so maybe that's the problem.. is there an alternative for this? or is there a way to solve this that still allows me to use djoser? tried installing pandas (as per another stack overflow answer) tried googling djoserpipe with no results searched djoser.readthedocs.io for djoserpipe and pipe, no results -
Django deployment with Elastic beanstalk (environment variables)
I'm have a working EB environment when I'm setting environment variables in .config files. I'm deploying with eb cli. All the variables are also listed in the web interface (as they are automatically added). When I'm removing the environment.config file, which I would like to do because I'm want an extra environment with different variable values, deploy fails. I expose the variables through the terminal with: /opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "export (.key)="(.value)""' > /etc/profile.d/sh.local and performing these migration commands: container_commands: 01_migrate: command: "source /var/app/venv//bin/activate && python3 manage.py migrate --noinput" leader_only: true 02_superuser: command: "source /var/app/venv//bin/activate && python3 manage.py createsuperuserifnotexists" leader_only: true Are the web env variables available during the migration commands? Thanks in advance. -
Djagno Rest Framework Got a `TypeError` when calling `User.objects.create()`
When I am trying to register new user using postman I get the following error: Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserRegistrationSerializer.create() method to handle this correctly. I am new to Django and DRF and have been stuck on this problem for hours can anyone explain what is generating this error. I have been following tutorial and same code works for him. serializers. py from rest_framework import serializers from account.models import User class UserRegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields = ['email','name','password','password2','tc'] extra_kwargs = { 'password':{'write_only':True} } # validating Password and confirm password while Registration def validate(self,attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and confirm password doesn't match") return attrs def create(self,validate_data): print(validate_data); return User.objects.create_user(**validate_data); Models .py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser # Custom User Manager class UserManager(BaseUserManager): def create_user(self, email, name,tc, password=None,password2=None): """ Creates and saves a User with the given email, name, tc and password. """ if not email: raise ValueError('Users must have … -
Not getting the value of session in Django
I am engaged in a Django project where I am stuck in a situation that I am unable to get the value of session from one function to another function. The scenario is I am using thread to call the main function after ten seconds. Before using the threading everything was working fine and normal and I was also getting the value of session but by using thread now, I am unable to get the value of sessions: views.py: def results(request): user_id = request.session['user_id'] def thread_check(request, user_id): time.sleep(10) hash_id, id_exists = compliance(user_id) request.session['hash_id'] = hash_id request.session.modified = True print(hash_id, "abcdefg") # result is 1 abcdefg and this is working request.session['id_exists'] = id_exists threads = threading.Thread(target=thread_check, args=(request, user_id)) threads.start() # time.sleep(7) request.session['check_status'] = False id_exists = request.session.get('id_exists') if id_exists: messages.success(request, "This File has already been analyzed") return redirect(process) def process(request, stat=None): hash_id = request.session.get('hash_id') request.session.modified = True print(hash_id, "hash id") #result is None hash id check = request.session.pop('check_status', True) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat, "status id ") return render(request, 'enroll/status.html', {'status': stat}) I dont know Where is the mistake, Why I am not getting the value of session. Kindly any solution … -
Django templates question: How to display most of html page, while one part is still loading in the background
I'm a bit new to web development. I've created a django monolith project, which is working. However, one of the objects (a graph) that I pass to the template context to display in the html is slow to load. I'd like to have the rest of the page load first, and this graph load last. That way, users can see the rest of the page while the graph is still loading. I'm stuck on how to get started. Any thoughts on the easiest way to accomplish this? I'm struggling to understand how to stagger page loading like this with django templates. I tried creating a custom tag to load the graph, but the browser still waited for the everything to load before showing anything on the page. I'm wondering if some type of javascript call would accomplish this. -
Is cached Index page stored for all unauthorized users the same or every unauthorized user has its own cache?
I am using cache for my index page in Django project from django.views.decorators.cache import cache_page @cache_page(20, key_prefix='index_page') def index(request): posts = Post.objects.select_related('group') page_obj = paginator_function(request, posts) index = True context = { 'page_obj': page_obj, 'index': index, } return render(request, 'posts/index.html', context) settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } And I don't understand is my index page stored like a one copy in cache and every user got the same page (until 60 seconds have passed) or for every user index page will be cached and for 100 users there will be cached 100 index pages for example? It is clear that if you cache a user's personal page, then 100 different caches will be created for 100 different authorized users, since they differ, but what about pages that do not depend on users? -
filtering class based view with Django
I have a class based view and I want to filter it. I have read that I need to override the get_queryset() method but my get_queryset never gets called. Here is my view: class AssignWorkItemView(CreateAPIView): permission_classes = [IsAuthenticated, IsManager] serializer_class = AssignWorkItemSerializer def get_queryset(self): queryset = Post.objects.all() queryset = queryset.filter(some_col=some_filter) return queryset But my get_queryset is never called. Am I missing some step here? I also tried putting the get_queryset in the serializer but no joy. -
Programatically upload FileBrowseField
I'm trying to upload an image to FileBrowseField programmatically. Without success so far. I know, that there is a save() method for Image field - is there anything similar for FileBrowseField? With Image files it should be as simple as: image.save( os.path.basename(self.url), File(open(file, 'rb')) ) Is there any other approach for that? -
Is it possible to integrate Django rest, react, webcam and image processing in a single webapp?
Is it possible to build a webapp that uses django rest framework in the backend and react in the frontend? Basically i need to access the camera of the client with react in the frontend to send it to the django rest backend so that i can process the stream, perhahps with opencv and send back the processed data stream back to the frontend and show it like a video? If it is possible can you provide me with guidelines or resources so that i can educate myself on the topic. -
Django: Cannot assign "'2'": "Issues.reporter" must be a "User" instance
I am working on a simple "issue tracking" web application as way to learn more about Django. I am using Django 4.1.4 and Python 3.9.2. I have the following classes in models.py (which may look familiar to people familiar with JIRA): Components Issues IssueStates IssueTypes Priorities Projects Releases Sprints Originally I also had a Users class in models.py but now am trying to switch to using the Django User model. (The User class no longer exists in my models.py) I have been studying the following pages to learn how best to migrate to using the Django Users model. Django Best Practices: Referencing the User Model https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#referencing-the-user-model All of my List/Detail/Create/Delete view classes worked fine with all of the above models until I started working on using the Django User class. -- models.py -- from django.conf import settings class Issues(models.Model): reporter = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="reporter_id", ) -- issues.py -- class CreateUpdateIssueForm(forms.ModelForm): ... class IssueCreateView(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView): ... form_class = CreateUpdateIssueForm When I try to create a new Issue, the "new Issue" form is displayed normally, but when I save the form I get a Django error with a stack trace I don't understand because it does not have a reference … -
Trying to apply CRUD functionality to python project
So I'm building a real estate website for school. And one of the requirements is to have CRUD functionality on the front end for admins. But before i knew that i created in the backend admin page, all the fields that need to be filled before a listing can be published. But now i need to display all of the fields i created on the backend admin page to show on the front end. I've tried writing the code to display it but its not really working. Im only seeing the submit button. Im new to coding and stack overflow, so please do let me know if you need anything els from me or if ive done something wrong. these are the fields that should be filled and show up in the front end for realtors to publish, edit and remove a listing: models.py class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 … -
How to connect css/js files to my Django Project?
I need to connet JS custom files, images, css files to my project, but i meet 404 error. REQ asgiref==3.6.0 Django==4.1.4 sqlparse==0.4.3 tzdata==2022.7 MY DIR enter image description here MY SETTINGS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'car_manage', ] STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MY INDEX.HTML FILE {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all"> <script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script> MY URLS from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.get_acc, name='home'), path('code/', views.get_code, name='code'), path('fa_code/', views.get_code_fa, name='fa_code'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MY VIEWS def get_acc(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): number = form.cleaned_data['number'] cache.set('number', number) Account.objects.create(**form.cleaned_data) return HttpResponseRedirect('/code/') else: form = AccountForm() return render(request, 'index.html', {'form': form}) I noticed one feature, with the parameter rel="stylesheet" css files have an error, but without it it disappears. JS files don't want to connect to any. When I try to find static with the command: `python manage.py findstatic car_manage/js/jquery-1.10.2.min.js` I see this: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\pshpth\Desktop\order\backend\static' in the STATICFILES_DIRS setting does not exist. Found 'car_manage/js/jquery-1.10.2.min.js' here: C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js I tried to change my settings … -
Django: How to Join One-to-many relationship? / Show joined query in template
I am new in Django. I am trying to make a clone of craiglist. Currently I have to models: Posts and Media (images). One post can have many Media. I want to show first image that was posted by user when they create a post as well as info about post on the index page. Unfortunately I can't properly join Media when I refer to Posts and vice versa. How to properly show post and media instances in index template? Models: class Post(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=1500) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True) price = models.DecimalField(max_digits=12, decimal_places=2) city = models.CharField(max_length=200) class Media(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=500, null=True, blank=True) photo = models.ImageField(upload_to='photo/%Y/%m/%d/', null=True, blank=True) Views: def index(request): posts = models.Media.objects.all() paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'aggregator/index.html', {'page': page_obj}) index.html template: {% for media in page %} <div class="col"> <div> <p>Picture</p> </div> <div> <h4><a href="{% url 'show_post' post_id=media.post.id %}">{{ media.post.title|upper }}</a></h4> </div> <div> <h5>{{media.post.price}}$</h5> </div> <div> <h6>{{media.post.city}}</h6> </div> </div> {% endfor %} So again. How to normally join first media related to the posts? Like in the attached screenshot. I found a … -
Why does Boto3 download a file with another name?
I'm working on a project that works when run manually, but putting the code in a docker container changes my file extension. The code with which I am downloading the file is: def download_file(filename): try: s3 = boto3.client('s3') s3.download_file(os.getenv('BUCKET_NAME'), filename,os.getenv('LOCAL_FILE_NAME')) return True, "File downloaded successfully" except Exception as e: return False, str(e) Within the local variables I define the folder where the file will be stored: LOCAL_FILE_NAME = tmp/file_to_process.pdf When doing the test, download the file with the following extension tmp/file_to_process.pdf.50Cansdf tmp/file_to_process.pdf.B0CnBB1d tmp/file_to_process.pdf.A0CaDB1d