Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I use created_at__range to specify a range, the range is shifted by one day
I'm currently using the filter "created_at__range" to specify the first and last day of the month, but this code doesn't reflect the data registered today. this_month = datetime.datetime.today() first_day = datetime.datetime(this_month.year, this_month.month, 1) this_month = this_month.strftime('%Y-%m-%d') first_day = first_day.strftime('%Y-%m-%d') time = obj.filter(created_at__range=(first_day, this_month)).aggregate( time=Sum('time'))['time'] Currently, I'm using timedelta(days=1) to add a day, but if I do this, for example, if the date is 3/31, it will be 4/1 and the tally will be wrong. this_month = datetime.datetime.today() + timedelta(days=1) Why is this happening? If anyone knows how to improve it, I'd appreciate it if you could let me know. -
django social auth don't associate new users correctly
I am trying to use social auth in Django in my Django GraphQL API (an alternative to rest api). However, after I created the social auth I created a costume user which make things a bit complicated. Also, it worked at the begging very well but and it created the user called weplutus.1 very well, but later after I did few small changes that I don't think they coul matter atall, and I did migrations and migrate as well after that I don't know what helped exactly but it when new users register the social auth associate it the admin despite the admin have a different email. # settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****' DEBUG = True ALLOWED_HOSTS = ["*"] # TODO change this in preduction CORS_ORIGIN_ALLOW_ALL = True # TODO change this in preduction # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'corsheaders', 'api', 'django_filters', 'social_django', ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', … -
How can show which product is selected without submit
I create a category and product drop down menu, but when i select the category and press the select button it not show which category is selected same with product menu. I just want to show the message which category and product is selected. I used Django message but when i submit the page it show the product id. I want to show the selected category and product name before submit View.py class OrderProduct(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): allOrder = OrdersModel.objects.all() categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') predoct = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'product': predoct, 'allOrder': allOrder} return render(request, self.template_name, args) def post(self, request): productobj = self.request.GET.get('SelectProduct') if productobj: messages.info(request, productobj) try: data = self.request.POST.get orderProduct = OrdersModel( product_id=productobj, description=data('description'), quantity=data('quantity'), ) orderProduct.save() return redirect('orderProduct') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> <label> <select name="SelectProduct"> <option disabled="disabled" selected> Select Category</option> {% for products in product %} <option value="{{ products.id }}"> {{ products.name }} </option> {% endfor … -
How do I set the dialect for a SQLAlchemy connection pool with PostgreSQL in Django Python? Needed for pre-ping feature enabled
What I'm trying to achieve I need to activate the pre-ping feature for as SQLAlchemy db pool in Django Python. Error When I set the pre_ping property to True, I get the following error which says I need to pass a dialect to the connection pool when using the pre-ping feature: The ping feature requires that a dialect is passed to the connection pool. Code Code for the connection pool creator/handler: import psycopg2 from sqlalchemy import create_engine import traceback from mbrain import settings from dataClasses.EmptyObject import * import json import sqlalchemy.pool as pool from sqlalchemy.pool import QueuePool dbPool = None class DbPoolHelper: def ensurePoolCreated(self): global dbPool if dbPool != None: return self.createPool() def dbConnect(self): dbConfig = self.getDbPoolConfig() dbConnection = psycopg2.connect(user=dbConfig.user, password=dbConfig.password, dbname=dbConfig.dbName, host=dbConfig.host, port=dbConfig.port) print("=========== POOL CONNECTED =================") return dbConnection def createPool(self): dbConnection = self.dbConnect global dbPool dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5, pre_ping=True) print("=========== POOL CREATED =================") def execute(self, sql, sqlParams): try: global dbPool self.ensurePoolCreated() poolConnection = dbPool.connect() cursor = poolConnection.cursor() cursor.execute(sql, sqlParams) poolConnection.commit() result = cursor.fetchall() cursor.close() poolConnection.close() return result except Exception as e: print(e) return e def getDbPoolConfig(self): settingName = "pool" dbConfig = EmptyObject() dbConfig.host = settings.DATABASES[settingName]["HOST"] dbConfig.port = settings.DATABASES[settingName]["PORT"] dbConfig.user = settings.DATABASES[settingName]["USER"] dbConfig.password = settings.DATABASES[settingName]["PASSWORD"] dbConfig.dbName = … -
How do you set Django environment variables with venv on linux?
I've tried using Python's os, manually typing the variables into the terminal, and using a .env file to set my environment variables but always get raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Python import os os.environ['SECRET_KEY'] = '<my secret key>' Inside .env export SECRET_KEY=<my secret key> In the terminal echo $SECRET_KEY >>>os.getenv('SECRET_KEY') both manage to print the variable. Ubuntu 20.04.02 Django 3.1 Using VSCode I have double checked the correct venv activated. What am I doing wrong! Thanks -
Django Access id field from parent model with javascript
here is my problem : In my template, I want to access the primary key of a queryset element which is a child of a parent model where the id attribute "id" is explicitly given. I gave it to my template using JSON serialization but I can't access the fields of the parent model. But when I use the python interpreter, I have no problem to access it, just like if it was the child's attribute. Here is the code : models.py class Correspondant(models.Model): nom = models.CharField(max_length=70) id = models.IntegerField(primary_key=True) class GRP(Correspondant): numTel = models.CharField(max_length=70) libelle = models.CharField(max_length=70) views.py : def index(request): listeGRP = serializers.serialize("json",GRP.objects.all()) context={'listeGRP':listeGRP} return render(request, 'annuaire/index.html', context) and how I access the GRP attributes with javascript : var tabGRPs = JSON.parse('{{ listeGRP|safe }}'); console.log(tabGRPs[0]["fields"]); which gives the following result : Object { numTel: "333333", libelle: "CATC Test 1" } As you can see, there are not the attributes of 'Correspondant' which is a parent of 'GRP'. Anyone has any solution ? Thank you ! -
JS fetch multiple pics (as FormData) to Django to save
I'm sure this seems so basic but it's my first attempt to try to upload files to django using fetch and I'm not sure how to manipulate and access FormData in Django.This create so many non-working jpg files. How to fix it? HTML: <div> <textarea></textarea> <input type="file" multiple></input> <button onClick="dothis" >Sound</button> </div> JS: function dothis(){ let data = new FormData(); let input = event.target.previousElementSibling; for (let file of input.files){ d.append( "hello", file); } fetch("/images", { credentials: "include", method: "POST", mode: "same-origin", headers: { "Accept": "application/json", "Content-Type": "application/json", // or "multipart/form-data"?? "X-CSRFToken": csrf }, body: data }) .then(response => response.json()) .then(result => { console.log("Well?"); }) Django views.by: def images(request): print(request.body) form = request.body filename = 0 for f in form: filename += 1 with open(f"{filename}.jpg", "wb+") as f: f.write(form) return JsonResponse(status=201) -
Migrate SQLite to PostgreSQL in DRF
I am trying to change my DB from SQLite to PostgreSQL. The problem which I am facing the size of the SQLite after dumpdata is 1.96GB. and when I am trying to load data I am getting an error: MemoryError: Problem installing fixture The command which I am using to import is : python manage.py loaddata dumpdata.json I can't find any external way to insert this JSON file directly to PostgreSQL. Can you help me what will be the best way to loaddata to Postgresql? -
Django rest api without database
I would like to create one restful API from the django rest_framework, in that I wanted to get client's data to be saved in a specific text file in my project directory, Thanks in advance if any help is available regarding my issue. -
Request Line is too large (8192 > 4094)
I am using nginx and gunicorn to deploy my django project, when I use GET funcation posted data to server I get the error: Bad Request Request Line is too large (8192 > 4094) On nginx.conf I have: client_max_body_size 100g; client_header_buffer_size 512k; large_client_header_buffers 4 512k; Many methods on the Internet are changing "large_client_header_buffers" from 4 512k; but didn't fix the problem. Any help or explanation is welcome! Thank you. -
Can i have Django urls and Vue routes in the same project?
I started a Django app and i created the whole authentication layer using Django-Allauth, it already has quite some features such as email confirmation, password reset and two factor authentication. Now i realized that, since my app will be heavily interactive and with a lot of real time features, i'm going to need a Vue SPA to use with Django, so i'm thinking of creating the Vue SPA on the same server and domain and have Django as a Rest API. Here is my problem: since i already made the whole authentication part using Django templates and Django urls, if i separate the rest of the frontend from the backend, will i have to rewrite everything? Is it possible to have a Vue app and a Django backend app separated on the same domain where authentication is handled by Django templates and all the rest is a Vue app with vue routes and all the other interactions are handled by Django Rest Framework endpoints? So maybe something like this: urlpatterns = [ path('accounts/signup/', SignUpView.as_view(), name='signup'), #Django template path('accounts/login/', LoginView.as_view(), name='login'), #Django template ... ] And these are the only Django-handled urls where the page is rendered by Django views. Once … -
Form is not rendering with password_reset_confirm_view
I am trying to implement the Password Reset from Django auth views. The HTML is rendering and everything seems to work fine but the form is not visible. It shows None on the form field. I tried inspecting the element and it turns out to be blank inside the HTML form element. Here is the views of inbuilt reset password confirm: class PasswordResetConfirmView(PasswordContextMixin, FormView): form_class = SetPasswordForm post_reset_login = False post_reset_login_backend = None reset_url_token = 'set-password' success_url = reverse_lazy('password_reset_complete') template_name = 'registration/password_reset_confirm.html' title = _('Enter new password') token_generator = default_token_generator @method_decorator(sensitive_post_parameters()) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): assert 'uidb64' in kwargs and 'token' in kwargs self.validlink = False self.user = self.get_user(kwargs['uidb64']) if self.user is not None: token = kwargs['token'] if token == self.reset_url_token: session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN) if self.token_generator.check_token(self.user, session_token): # If the token is valid, display the password reset form. self.validlink = True return super().dispatch(*args, **kwargs) else: if self.token_generator.check_token(self.user, token): # Store the token in the session and redirect to the # password reset form at a URL without the token. That # avoids the possibility of leaking the token in the # HTTP Referer header. self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token redirect_url = self.request.path.replace(token, self.reset_url_token) return HttpResponseRedirect(redirect_url) # Display the "Password reset unsuccessful" … -
Django logger's level is not tracking INFO messages even though level is set to ERROR
I'm trying to create a simple logger, and I only want the logger to record ERROR (and not INFO or WARNING). I've set the level to logging.ERROR, and using messages using logger.info correctly does not appear. However, the funny thing is system message with level "INFO" are being tracked (2021-03-18 17:14:43,251 - django.utils.autoreload - INFO - file changed, reloading.). I don't really understand why this is happening since the example is INFO and not ERROR, and I'm not directly calling it use logger.info. import logging def create_logger(app_name): """Create a logging interface""" logging.basicConfig( filename='logs/example.log', level=logging.ERROR, encoding='utf-8', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(app_name) return logger logger = create_logger('test') # this is correctly logged logger.error('Test error') # this is correctly not logged logger.info('Test info') -
Djano remot user login via java script
In my django application hosted on heroku (https://ers-heatscreen-app.herokuapp.com) , i would like to authenticate users from an existing customer login on a productive homepage which is solved with java script. So when they login at https://shop.ers-heatscreen.com/login i would like to take the existing user an create a new user/login with existing user in my application. I have invested a ton of time in reading stackoverflow and django documentation, but cant puzzle things together.... Somehow is the best solution, to set a remote_user in django and solve the problem with django MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', ] .... AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', ] Maybe you have some hints/code snippeds/links for me to point me to the right direction. Would really appreciate any help. If you need some more information, i can post further information anytime. -
How to show products & orders of related merchants accounts in django rest framework?
I built an e-commerce project using Django rest framework. For now, the admin can add products directly from the default django backend. Now, the client's requirements have increased, and we have to build a merchant dashboard. Now there will be many seller accounts who will be using that dashboard after registering as a seller from the frontend. Now, in that dashboard (in the frontend), I have to show the products added only by that merchant. For eg: Mobile phone merchants should be able to see only their products ie phones and clothes merchants should be able to see their products only after adding them. The same goes for the order view as well. Until now I haven't associated the user field in the products as it was not required. Also, the order is not done by the seller, but by customers only. Hope I have explained. My models: class Product(models.Model): AVAILABILITY = ( ('in_stock', 'In Stock',), ('not_available', 'Not Available',), ) WARRANTY = ( ('no_warranty', 'No Warranty',), ('local_seller_warranty', 'Local Seller Warranty',), ('brand_warranty', 'Brand Warranty',), ) SERVICES = ( ('cash_on_delivery', 'Cash On Delivery',), ('free_shipping', 'Free Shipping',), ) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) … -
Getting the uploaded images in Django
I have a class with multiple images that can be uploaded. I am trying to use Bootstrap Carousel for a slide show of the images, but I am having a hard time getting it. Models.py class Content(models.Model): title = models.CharField(max_length=250) content = models.TextField(max_length=1000) website = models.URLField() github = models.URLField() def __str__(self): return self.title def get_image_filename(instance, filename): title = instance.post.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename) class Images(models.Model): post = models.ForeignKey(Content, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') Views.py def home(request): content = Content.objects.all() name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') if request.method == "POST": if not name and not email and not message: content = 'name: ' + name + '\n' + 'email: ' + email + '\n' + '\n' + message send_mail('Email from Portfolio', content, 'email', ['email'], fail_silently=False) messages.success(request, "Your Email has been sent") return redirect('home') else: return render(request, 'appOne/home.html', {'content':content}) @login_required def post(request): ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=3) #'extra' means the number of photos that you can upload ^ if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if postForm.is_valid() and formset.is_valid(): post_form = postForm.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: #this helps to not crash if the user #do not … -
GeoDjango + Postgis missing functions
So I've been using a Postgres database with the extension Postgis installed, and then using a Django setup to draw spatial data on a Leaflet OpenStreetMap. It has been a bit difficult translating my sql queries to the database functionality that Django is using whenever you're communicating with your database. Often I seem to be missing Postgis functions such as ST_LineCrossingDirection or ST_FrechetDistance. How do I get to use those functions along with .annotate and .filter from Django without having to write custom sql queries and executing those? I've tried to look into F() and Func() from Django as well, but I don't think that solves my issue as it seem to be using built in aggregate functions. I also tried to execute RawSQL in an annotate function to perform the function ST_LineCrossingDirection but it would require me to write a WHERE clause and the condition is something I'm not aware of until I get to the filter() call where I'm using intersects() between two geometries. Anyway .. If anyone knows how to use what I assume is missing Postgis functions please let me know. Because my code is getting quite messy and ineffective. Thanks, and all help is appreciated! -
Connect fields from 2 models with a primary key
I'm working on an already built project. There are 2 different model, product and stock. Products model has field which is sub_category and stock has main_category. Stock has a product_id which is a foreign key to the Product. I also need to get information from Product which is product_sub_category with product_category_id in a serializer. class Product(BaseModel): product_id = models.CharField(default=randomword(5), null=False, blank=True, max_length=100, unique=True) product_sub_category_id = models.ForeignKey(Product_sub_category, on_delete=models.SET_NULL, null=True, blank=True) class Vendor_Stock(BaseModel): vendor_id = models.ForeignKey(Vendor_management, on_delete=models.SET_NULL, null=True, blank=True) product_id = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) product_category_id = models.ForeignKey(Product_category, on_delete=models.SET_NULL, null=True, blank=True) What would a serializer look like for this? -
Upload python script and load/use it in runtime in django
I need to upload user created python script and load/use it in runtime in django. I tried several approaches like using importlib and other django module like SourceFileLoader. But it seems like the import is failed with 'Permission error'. Ideally, I would like to store the uploaded file in a folder which is at the level of my django project. What's the correct approach for this functionality, particularly the module loading part? -
How to handle editing conflicts in Django forms?
Imagine the following situation: Two users, Alice and Bob, are using a Django form to edit the same object simultaneously. For the purpose of this example, let's use the following model: class Book(models.Model): title = models.TextField() description = models.TextField() Alice edits the book to change its title. Meanwhile, Bob edits the book to change its description. Now, if Bob is the last one to click the "Save" button, his form will "win" and only the description of the book will have been changed. Otherwise, if Alice is the last one to save, only the title will have been changed. Ideally, however, after both forms have been saved, the database should contain the title from Alice, and the description from Bob. I can think of a few possible solutions to prevent this from happening: Locking the form. As soon as Alice requests the book edit form, she acquires a lock that is released after she clicks "Save". When Bob tries to request the same form, he could get an error or warning message that Alice is already editing the same book. The problem here is if course dealing with stale locks. Checksumming the data being edited. The form could contain a … -
Django: maintain sessions across multiple domains with different backend
I have two websites hosted on the same server (aws instance), let's say: web1.domain.com and web2.domain.com Every time a user access one website or another, they will have to log in. If a user accesses from web1 (already logged in) to web2, I want to avoid the user having to log in again. The backend is different: web1 (Python, django) web2 (PHP, mediawiki) Both websites use Mysql and Apache server. I have found this but it does not solve my question completely: Django: maintain sessions across multiple domains I would like to know if there is any way to achieve it. For now, options such as SSO via SAML are ruled out due to complexity. -
Auto printing orders from sql using django/laravel
Is there any possibility to create app (django, laravel) - that would get data from database, table called orders and would automatically create pdf with data and download it? Let's say, i've got 5 new orders, each for different address and different goods. App should automatically create pdf and download for each of those 5 orders. It could also be a react app getting orders from API. Is this possible? Thanks in advance. -
Problem about making correctly link a URL with a webpage
models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator #from django.contrib.postgres.fields import ArrayField # Create your models here. class locationData (models.Model): locationID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) population = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) apiEndpoint = models.URLField (max_length = 256) resourceURL = models.URLField (max_length = 256) class dateData (models.Model): entryID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) date = models.DateField (auto_now = False, auto_now_add = False) confirmedCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) deathCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView, DetailView from database.models import locationData, dateData # Create your views here. class viewLocationData (DetailView): template_name = "locationData.html" model = locationData def get_context_data (self,**kwargs): location = self.kwargs['location'] context = super().get_context_data (**kwargs) context ['location'] = locationData.objects.get (pk = location) return context app/urls.py from django.urls import path from database import views urlpatterns = [ path ('location_data/<int:location>', views.viewLocationData.as_view(), name = 'location-data') ] config/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path ('database/', include ('database.urls')) ] locationData.html <h1>Location Data</h1> <table> <tr> <td>Location Name</td> <td>{{location.name}}</td> </tr> <tr> <td>Current Estimated Population</td> <td>{{location.population}}</td> </tr> … -
Issue Installing Locustio(0.7.5) Package
macOS == 10.15.7 || Django Project || Python 3.6.7 When I'm trying to install locustio version 0.7.5 package from pip it is giving error.I have tried fix mentioned in all versions of answer that were similar to this everywhere but no progress. When I run the following command :- pip install locustio==0.7.5 Collecting locustio==0.7.5 Using cached locustio-0.7.5-py3-none-any.whl Requirement already satisfied: requests>=2.9.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from locustio==0.7.5) (2.25.1) Collecting flask>=0.10.1 Using cached Flask-1.1.2-py2.py3-none-any.whl (94 kB) Requirement already satisfied: msgpack-python>=0.4.2 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from locustio==0.7.5) (0.5.6) Collecting gevent==1.1.1 Using cached gevent-1.1.1.tar.gz (2.0 MB) Requirement already satisfied: greenlet>=0.4.9 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from gevent==1.1.1->locustio==0.7.5) (1.0.0) Requirement already satisfied: Werkzeug>=0.15 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (1.0.1) Requirement already satisfied: click>=5.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (7.1.2) Requirement already satisfied: itsdangerous>=0.24 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (1.1.0) Requirement already satisfied: Jinja2>=2.10.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (2.11.3) Requirement already satisfied: MarkupSafe>=0.23 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from Jinja2>=2.10.1->flask>=0.10.1->locustio==0.7.5) (1.1.1) Requirement already satisfied: certifi>=2017.4.17 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (2020.12.5) Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (1.26.4) Requirement already satisfied: idna<3,>=2.5 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (2.10) Requirement already satisfied: chardet<5,>=3.0.2 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (4.0.0) Building wheels for collected packages: gevent Building wheel for gevent (setup.py) ... error ERROR: Command errored out with exit status 1: … -
Request not sending file in django test
I want to test a view that is suppose to receive files attached with the request. my django test: TEST_DIR = "myapp/tests/test_data/" file_name = "some_resume.pdf" email_data = { # ... } api = APIClient() with open(FILE_DIR + file_name, "rb") as fp: response = api.post( "/api/v1.0/emails/receive/", data=email_data, files={"resume": fp}, # pass file handler open with byte mode format="multipart", # use multipart format ) # test some stuff but when I print the files attached to the request in the View I get nothing: print(request.FILES) # <MultiValueDict: {}> I checked everywhere and the format for my api request looks file. Also, my view works fine when I test with shell sending request with with python requests library. Am I missing anything? Could id be somehow related to my test environment or some obscure middlewares?