Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering site with specific tags in Django while keeping all site tags aggregated in annotation field
Let's say I have the following django model: class Tag(models.Model): key = models.CharField(max_length=64, unique=True) class Site(models.Model): key = models.CharField(max_length=64, unique=True) tags = models.ManyToManyField(Tag, through='SiteTag') class SiteTag(models.Model): site = models.ForeignKey(Site, on_delete=models.RESTRICT) tag = models.ForeignKey(Tag, on_delete=models.RESTRICT) Where a site can have multiple tags using explicit Many-to-Many relationship. When I filter site with a specific tag in the following query other tags are filtered out where I mean give me sites with this tags and show all tags those sites have: Site.objects.filter(tags__key__in=['type-1', 'type-2'])\ .annotate(tags=ArrayAgg("tags__key", distinct=True, filter=Q(tags__isnull=False))) Then it indeed retrieve sites with either type-1 or type-2 but if a selected site has the type-3 tag I also want to collect it in the ArrayAgg aggregation. Unfortunetly with this query I will only have ["type-1", "type-2"] in annotated tags field instead of ["type-1", "type-2", "type-3"]. How can I filter sites using this criterion and still have all tags collected in the annotate section. -
How to send data to a particular user in django channels?
This is my class: class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField("Employee") def save(self, *args, **kwargs): super().save(*args,**kwargs) channel_layer = get_channel_layer() data = {"current_obj":self.name} async_to_sync(channel_layer.group_send)( "test_consumer_group_1",{ 'type':'send_notification', 'value':json.dumps(data) } ) This is my consumer file. class TestConsumer(WebsocketConsumer): def connect(self): self.room_name="test_consumer" self.room_group_name = "test_consumer_group_1" async_to_sync(self.channel_layer.group_add)( self.channel_name, self.room_group_name ) self.accept() print('connected..') self.send(text_data=json.dumps({'status':'connected'})) def recieve(self, text_data): print(text_data) def disconnect(self, *args, **kwargs): print('disconnected') def send_notification(self, event): print("send_notification called") print('Event...', event['value']) user = self.scope['user'] print(user) # Check if the user is authenticated and is a member of the team ''' if user.is_authenticated and user.employee in self.team.members.all(): self.send({ "type":"websocket.send", "text":event['value'] }) ''' This is my asgi.py file: import os import app.routing from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( app.routing.websocket_urlpatterns ) ), }) When an object of MyClass is created, send_notification is called. Now I want to ask two things: Inside send_notification, user = self.scope['user'] always returns anonymous user, even if user is authenticated. I want to send notification to particular users onlyi.e. employees who are added in MyClass object and are logged in, instead of broadcasting the message How to do that? -
Django dynamic model fields dependent on uploaded data in other model
I would like to create a model with fields that correspond to the column names of a csv file that is uploaded by the user. I use the model CsvCreate to let the user upload a csv file and to create instances of the model Data, where an instance is a row in the csv file. This works fine, but I have to specify the fields in Data beforehand. However, the column names in the csv file could vary. What I want is to have a model with dynamic fields that are dependent on the uploaded csv file. Model CsvCreate: class CsvCreate(models.Model): file_name = models.FileField(upload_to='csvs') uploaded = models.DateTimeField(auto_now_add=True) selected = models.BooleanField(default=False) measurement_number = models.IntegerField(blank=True, null=True) notes = models.TextField(blank=True, null=True) dataset = models.ForeignKey('Dataset', on_delete=models.CASCADE) units = models.CharField(max_length=100, blank=True, null=True ) def __str__(self): return f"File name: {self.file_name}, file id: {self.id}, uploaded at {self.uploaded}, selected: {self.selected}" def save_csvs(self): obj = self with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) values = [obj] units = [] dict_list = [] for i, row in enumerate(reader): if i < 2: pass elif i == 2: for i in range(0,len(row)): units.append(row[i]) else: for i in range(0,len(row)): values.append(row[i]) data_dict = dict(zip(parameters.parameters, values)) dict_list.append(data_dict) values = [obj] django_list = … -
ATOM PACKAGE INSTALLATION
I am unable to find packages in ATOM. It continuously showing some certifications error .Can anyone help me out please Please ans to my question with necessary solutions -
Chromedriver error on Django DigitalOcean App Platform
I'm currently developping a web app using django and the App platform on digitalocean. My web app uses selenium and chromedriver, I have found a way to install chromedriver using python libs such as chromedriver_binary on pip but the app can't open it and throws me an error : Message: Service chromedriver unexpectedly exited. Status code was: 127 This error most likely means that some dependencies and libs are not available and leads to the script crashing. Here's my current code inside views.py : from selenium import webdriver import chromedriver_binary import time from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium_stealth import stealth import undetected_chromedriver as uc from selenium.webdriver.chromium.options import ChromiumOptions from selenium.webdriver.common.by import By import urllib.request from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import UnexpectedAlertPresentException from selenium.common.exceptions import NoSuchElementException from googleapiclient.discovery import build from urllib.parse import urlsplit def get_webdriver(url): options = webdriver.ChromeOptions() options.add_argument('--disable-extensions') options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument('--no-sandbox') options.add_argument('start-maximized') options.add_argument('disable-infobars') options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-browser-side-navigation') options.add_argument('--disable-gpu') driver = webdriver.Chrome() driver.get(url) return driver Is there a way (maybe using another lib, or a whole other solution) to deploy chromedriver on this django app ? Thank you a lot ! -
How to handle 300 parameters in Django Model / Form?
I develop an app for creating products in online shop. Let's suppose I have 50 categories of products and each of these has some required parameters for product (like color, size, etc.). Some parameters apper in all categories, and some are unique. That gives me around 300 parameters (fields) that should be defined in Django model. I suppose it is not good idea to create one big database with 300 fields and add products that have 1-15 parameters there (leaving remaining fields empty). What would be the best way to handle it? What would be the best way to display form that will ask only for parameters required in given category? -
I followed the django example exactly. But it doesn't work
** I followed the django example exactly. But it doesn't work. Web page just show the rocket to me.** my project name: web app name: main web.settings.py `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ]` web.urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('main/', include('main.urls')), path('admin/', admin.site.urls), ] main.urls.py => from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] main.views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") I hope web page shows "Hello, world. You're at the polls index." to me. -
How do you manage testing error Django projects?
I need to create a blog post app in which I am stuck in testing all test cases , I need a user which can remain logged in throughout the testing phase so that I can use the same logged in user in blog and post and update_post apis but I am unable to do so can you please suggest !! def test_login(client, user_data): # with unittest.mock.patch('django.contrib.auth.authenticate') as mock_authenticate: # mock_authenticate.return_value = authenticate( # request=client.post(reverse('login'), user_data, format='json'), # backend='django.contrib.auth.backends.ModelBackend' # ) with unittest.mock.patch('django.contrib.auth.authenticate') as mock_authenticate: user = CustomUser.objects.create_user(**user_data) mock_authenticate.return_value = user response = client.post(reverse('login'), user_data, format="json") assert response.sstatus_code == 200 this is my login api and I want this user to be logged in throughout all apis without using SESSIONS -
Can't filter empty fields in Django
I want to get a list of users that have provided an email in my database using Django. This is my query: list(App.objects.exclude(admins__email='').values('admins__email')) which strangely exclude everything and gives : [] although when i run: list(App.objects.all().values('admins__email')) i can see a list of user emails and NOT all of them are empty: [{'admins__email': 'example@gamil.com'}, {'admins__email': ''}, {'admins__email': ''}, {'admins__email': ''}, {'admins__email': 'example2@gamil.com'}, {'admins__email': 'example3@gamil.com'}, {'admins__email': ''}, ...] i expect to get this list: [{'admins__email': 'example@gamil.com'}, {'admins__email': 'example2@gamil.com'}, {'admins__email': 'example3@gamil.com'}] ps: somehow i can get the correct list with list(User.objects.exclude(email__exact='').values('email')) but in this context, I need to apply some filters to my App and therefore i need to get the first query to work. -
django orm multiple points ranking
I've a model name Points which store the user points on the base of it's actions. class Points(CreateUpdateModelMixin): class Action(models.TextChoices): BASE = 'BASE', _('Base') REVIEW = 'REVIEW', _('Review') FOLLOW = 'FOLLOW', _('Follow') VERIFIED_REVIEW = 'VERIFIED_REVIEW', _('Verified Review') REFERRAL = 'REFERRAL', _('Referral') ADD = 'ADD', _('Add') SUBTRACT = 'SUBTRACT', _('Subtract') user = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField() action = models.CharField(max_length=64, choices=Action.choices, default=Action.BASE) class Meta: db_table = "diner_points" Please note that there are multiple rows for the same user. For the past few days I'm trying to write a query to get the total_points of the use and also the rank of that user. Using: Django 3.2 MySQL 5.7 I want to know input of you guys. Thanks. I wrote this query and many other like it. But none of them give the results I want. Let's suppose the data is something like this. user points 771 221 1083 160 1083 12 1083 10 771 -15 1083 4 1083 -10 124 0 23 1771 The current query I have written is this... innerquery = ( DinerPoint.objects .values("user") .annotate(total=Sum("points")) .distinct() ) query = ( DinerPoint.objects .annotate( total = Subquery( innerquery.filter(user=OuterRef("user")).values("total") ), rank = Subquery( DinerPoint.objects .annotate( total = Subquery( innerquery.filter(user=OuterRef("user")).values("total") ), rank=Func(F("user"), function="Count") … -
Django returns model objects in random order after app rename
I've renamed an app in my Django project, trying to follow all 'best practices', that is, I renamed project folders, migrations (in project + PostgreSQL), DB content types and table names. Everything works fine, except one thing: the order of the objects returned by myfavmodel.objects.all() appears to be random, that is, NOT sorted by increasing ID, yet it is always the same when I call myfavmodel.objects.all(). Even more strange is that some models in the renamed app show this behaviour while others show the normal one, that is, their objects are returned sorted by increasing ID. I can solve the problem rather easily by adding ordering = ['id'] to the Meta class of my models but I would like to understand what is causing this behaviour. -
After running "python manage.pr makemigrations" indjango, models are still left un migrated with this message on CLI
It is impossible to add a non-nullable field 'core' to event without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. enter image description here my models -
How to make Django view accessible only when a GET request is issued by HTMX?
I am trying to learn HTMX for using it with Django. I have a simple HTMX button that when you click you get some filtered results on the page. The problem is that when users go to the specified URL provided for the purpose of showing content through the GET request, they can see the content of the page. They should only be able to see this content when they press the HTMX button though, not by navigating to the URL HTMX gets in order to show the content. Is there any way on how to handle this? -
How to change json view in django serializer?
This is my serializer.py class RefbookSerializer(serializers.ModelSerializer): class Meta: model = Refbook fields = ['id', 'code', 'name'] And it's my views.py class RefbookAPIList(ListCreateAPIView): queryset = Refbook.objects.all() serializer_class = RefbookSerializer def get_queryset(self): date = self.request.query_params.get('date', None) if date: query = Refbook.objects.filter(versions__date__lte=date).distinct() return query return super().get_queryset() Now, on request GET api/v1/refbooks/?date=2023-02-01 it returns a response like: [ { "id": 3, "code": "1", "name": "..." }, { "id": 4, "code": "2", "name": "..." } ] But i want like this: { "refbooks": [ { "id": 3, "code": "1", "name": "..." }, { "id": 4, "code": "2", "name": "..." } ] } How can i add this "refbooks" key and curly braces around it? -
Form with different target urls to send the POST to
I have one view displaying a form. Now, depending on the button the user chooses, I want to have the data processed in a different way. These "different ways" correspond with different views that I want the POST request go to. Please help me building a form with multiple buttons leading to different urls/views. <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Process form with view ONE"> <input type="submit" value="Process form with view TWO"> <input type="submit" value="Process form with view THREE"> </form> My problem here is that the action attribute of the form tag defines where this POST request is going to. How can I change that target url via multiple buttons? I know I could also handle this logic on the server-side. But the question is: Do I have to? If not, please show me the way -
Django filter query using Q
Can anyone help me. Im trying to use a django filter with Q. This is my function def get_first_time_customer_ids(year: int, month: int) -> QuerySet: return Customer.objects.filter( Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__year=year, bookings__pickup_time__month=month) & ~Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__lt=date(year, month, 1)) ).distinct().values_list('id', flat=True) What im trying to achieve is to yield all the customer id that have the first time booking for any given year and month. But its failing on my test case. My test case : def test_get_first_time_customer_ids(self) -> None: customer_1 = Customer.objects.create(name="Customer 1") customer_2 = Customer.objects.create(name="Customer 2") Booking.objects.bulk_create([ Booking(number="A", customer=customer_1, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 2, 4, 12), route_id=1, vehicle_category_id=1), Booking(number="B", customer=customer_1, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 1, 5, 12), route_id=1, vehicle_category_id=1), Booking(number="E", customer=customer_2, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 2, 10, 12), route_id=1, vehicle_category_id=1) ]) ids = get_first_time_customer_ids(2023, 2) self.assertTrue(customer_2.id in ids) self.assertFalse(customer_1.id in ids) Its failing in the last line. The customer id for customer_1 included in query, it shouldnt have. Any help is appreciated -
Django models default value based on parent length
I'm making an app that has multiple exams and multiple questions for each exam. This is my current 'Question' model: class Question(models.Model): exam = models.ForeignKey(Exam, related_name='questions', on_delete=models.CASCADE) question = models.TextField() explanation = models.TextField(blank=True, null=True) TOPICS = [ ('NA', 'Not Available'), ('Algebra', 'Algebra'), ('Geometry', 'Geometry'), ('Trig', 'Trigonometry'), ('Calc', 'Calculus'), ('Chem', 'Chemistry'), ('Geology', 'Geology'), ('Physics', 'Physics'), ('Reading', 'Reading'), ('Writing', 'Writing'), ('Spelling', 'Spelling'), ('Comprehension', 'Reading Comprehension'), ] topic = models.CharField(max_length=20, choices=TOPICS, default='NA') order = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) attempts = models.IntegerField(default=0, editable=False) correct_attempts = models.IntegerField(default=0, editable=False) class Meta: unique_together = ['exam', 'order'] def __str__(self): return f'{self.exam} - Q{self.order}' You can pretty much ignore all the fields except the 'order' field. This field shows what order the question will appear on the exam. I would like for the default value of this order field to be the number of existing questions in the exam + 1. For example, if my exam has two questions in it already, and I'm trying to add a third question, the order of this question will default to '3' unless I manually change it. I know this doesn't work, but this solution would work similarly to this line of code: default=Question.objects.filter(exam=self.exam).count() + 1 I'm inexperienced in creating functions for … -
For loop and with tag in a Django template
I have a context built in this way: def end(request): numero_debitori = request.session['numero_debitori'] dati_totali = {'numero_debitori': numero_debitori} if request.session['tipo_creditore'] == 'PF': dati_totali['creditore'] = { 'tipo': 'Persona Fisica', 'dati': { 'nome': request.session[f'nome'], 'cognome': request.session[f'cognome'], 'luogo_di_nascita': request.session[f'luogo_di_nascita'], 'data_di_nascita': request.session[f'data_di_nascita'], 'comune_di_residenza': request.session[f'comune_di_residenza'], 'indirizzo_di_residenza': request.session[f'indirizzo_di_residenza'], 'email': request.session[f'email'], 'pec': request.session[f'pec'], 'codice_fiscale': request.session[f'codice_fiscale'], 'partita_iva': request.session[f'partita_iva'], } } elif request.session['tipo_creditore'] == 'PJ': dati_totali[f'creditore'] = { 'tipo': 'Persona Giuridica', 'dati': { 'denominazione_sociale': request.session[f'denominazione_sociale'], 'comune_sede_principale': request.session[f'comune_sede_principale'], 'indirizzo_sede_principale': request.session[f'indirizzo_sede_principale'], 'email': request.session[f'email'], 'pec': request.session[f'pec'], 'codice_fiscale': request.session[f'codice_fiscale'], 'partita_iva': request.session[f'partita_iva'], } } for i in range(numero_debitori): if request.session[f'tipo_{i}'] == 'PF': dati_totali[f'debitore_{i}'] = { 'tipo': 'Persona Fisica', 'dati': { 'nome': request.session[f'nome_{i}'], 'cognome': request.session[f'cognome_{i}'], 'luogo_di_nascita': request.session[f'luogo_di_nascita_{i}'], 'data_di_nascita': request.session[f'data_di_nascita_{i}'], 'indirizzo_di_residenza': request.session[f'indirizzo_di_residenza_{i}'], 'codice_fiscale': request.session[f'codice_fiscale_{i}'], 'partita_iva': request.session[f'partita_iva_{i}'], } } elif request.session[f'tipo_{i}'] == 'PJ': dati_totali[f'debitore_{i}'] = { 'tipo': 'Persona Giuridica', 'dati': { 'denominazione_sociale': request.session[f'denominazione_sociale_{i}'], 'sede_principale': request.session[f'sede_principale_{i}'], 'codice_fiscale': request.session[f'codice_fiscale_{i}'], 'partita_iva': request.session[f'partita_iva_{i}'], } } context = {'dati_totali': dati_totali} return render(request, 'end.html', context) Inside end.html I'm trying to access to f'debitore_{i}' in this way but nothing was shown: {% for i in dati_totali %} {% with debitore_|add:i as debitore %} {{dati_totali.debitore.tipo}} {% endwith %} {% endfor %} I don't know what's wrong with this code. I also tried to print the data inside the terminal to check if the data inside the … -
WebSocket connection to failed
Locally, everything works fine. When I deploy the applications to Railway I get a "WebSocket connection to failed" error. ` application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(chat.routing.websocket_urlpatterns))), }) websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), ] const chatSocket = new WebSocket('wss://' + 'appdvibe.up.railway.app' + '/chat/' + roomName + '/'); -
displaying pics in django tempaltes unevenly
I am new to Django and I have a html template which have uneven pics but i have no idea how to do the for in my html file while getting the pics from DB. can someone please help me? this is the thing that I want? enter image description here I have no idea for this problem -
How to use different python.exe in Pipenv environment, corporate windows defender firewall, Django REST API
I have an issue where the windows defender firewall will only allow connections to python via a specific folder (e.g. C:Anaconda/python.exe) (This is a conda environment) I would like to run an API in a virtual environment, however that environment uses another folder. (e.g. C:VEnv) Rather than update the packages in the conda environment, I would much prefer the control of a virtual environment for the API, but it cannot be reached outside of the PC running it due to the PC windows firewall restrictions. Is there some sort of setting that would allow me to use the python.exe from another folder from within the venv? Am I in denial that there is any solution to this problem other than opening up the defender firewall? I have tried running the API in the virtual environment (maybe im missing a setting?) No luck. I have tried running the API in the conda environment, and a whole load of other stuff broke, which will take a long time to fix. I do have the API running from the virtual environment being accessed within its own PC, but externally there is nothing. -
Django record and save mp4
I'm new to Django. I'm trying to record a video in the browser than automatically save that to the server as an mp4 file. I managed to do it, but the videos are sent as a blob and saved in the database. But I would need an mp4 file on the server. For recording I'm using MediaRecorder. BTW this only needs to work on desktop, not on mobile. This is my js code: const videoElem = document.getElementById('stream-elem') var startBtn = document.getElementById('start-stream') var endBtn = document.getElementById('stop-media') console.log("recorder"); var recorder; const settings = { video: true, audio: true } startBtn.addEventListener('click', function (e) { console.log("StartStream button is clicked"); navigator.mediaDevices.getUserMedia(settings).then((stream) => { console.log(stream); videoElem.srcObject = stream recorder = new MediaRecorder(stream) console.log(recorder); recorder.start(); const blobContainer = []; recorder.ondataavailable = (e) => { blobContainer.push(e.data) } recorder.onerror = (e) => { return console.log(e.error || new Error(e.name)); } recorder.onstop = (e) => { console.log(window.URL.createObjectURL(new Blob(blobContainer))); var newVideoEl = document.createElement('video') newVideoEl.height = '400' newVideoEl.width = '600' newVideoEl.autoplay = true newVideoEl.controls = true newVideoEl.innerHTML = `<source src="${window.URL.createObjectURL(new Blob(blobContainer))}" type="video/mp4">` document.body.removeChild(videoElem) document.body.insertBefore(newVideoEl, startBtn); var formdata = new FormData(); formdata.append('blobFile', new Blob(blobContainer)); fetch('/upload', { method: 'POST', body: formdata }).then(()=>{ alert('streamed video file uploaded') }) } }) }) endBtn.addEventListener('click', function (e) { videoElem.pause(); … -
Advice on Django user profile edit views
I'm building a Django app that will have users and profile models associated with them and they should have the ability to edit their profile in a view. As I see there are two similar but slightly different approaches how that could be done. An UpdateView could be used that retrieves a pk from the url and then verifies if the pk corresponds to the actual authenticated user, for instance: class ProfileUpdateView(UpdateView): model = Profile fields = ['field1', 'field2'] def get_object(self, queryset=None): obj = super().get_object(queryset=queryset) if obj.user != self.request.user: # If the object user does not match the logged in user, # raise a 404 Not Found exception. raise Http404("You do not have permission to edit this profile.") return obj Or an alternative way that would check/ reference the current user via Django's authentication backend, for instance: def profile_update(request): profile = request.user.profile form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() context = {'form': form} return render(request, 'profile_update.html', context) The main question is a bit generic, hence the name 'advice' in the post title, but are there any benefits/ risks associated with one or the other way of implementing a profile edit view that one should definitely consider when choosing … -
Unapplied migrations warning with latests version of code and data
I pulled the latest version of the master branch (which is currently running in production) and downloaded a fresh dump of the production base. I restored the database, launched it locally - I get a message that I have 10 unapplied migrations. At the same time, CI / CD is configured in the project, all migrations during the deployment process are applied automatically. Where could non-applied migrations come from? I can only explain this by the fact that someone edited the table with migrations on the prod, but there may be other versions? If I try to apply the migrations locally, then the InconsistentMigrationHistory error comes out (one of the migrations was applied earlier than the one on which it depends), but this is the next problem for me (although it is obviously related to the first one) -
How to save processed excel file (by pandas) in django model?
I want user to upload its excel file, then the file will be processed with pandas and this processed will be saved in model. However, I have an error: Traceback (most recent call last): File "C:\Corrila\DJ\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Corrila\DJ\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Corrila\DJ\lemonshop\demoapp\views.py", line 108, in upload_file form.save() File "C:\Corrila\DJ\lemonshop\demoapp\forms.py", line 43, in save new = pd.read_excel(self.file) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\util\_decorators.py", line 211, in wrapper return func(*args, **kwargs) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\util\_decorators.py", line 331, in wrapper return func(*args, **kwargs) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\excel\_base.py", line 482, in read_excel io = ExcelFile(io, storage_options=storage_options, engine=engine) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\excel\_base.py", line 1652, in __init__ ext = inspect_excel_format( File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\excel\_base.py", line 1525, in inspect_excel_format with get_handle( File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\common.py", line 713, in get_handle ioargs = _get_filepath_or_buffer( File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\common.py", line 451, in _get_filepath_or_buffer raise ValueError(msg) Exception Type: ValueError at /upload/ Exception Value: Invalid file path or buffer object type: <class 'type'> I have modelform to upload an excel file and process it in pandas: ModelForm: class FileForm(forms.ModelForm): file = forms.FileField class Meta: model = FilesModel fields = ['title', 'file'] def save(self, commit=True): m = super(FileForm, self).save(commit=False) # do custom stuff if commit: new = pandas.read_excel(self.file) new = new.mean().to_excel self.file = new m.save() …