Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

570
Views
django upload file, process pandas and download as csv

I built an app which allows the user to upload a file. On the other hand, I have some python script which takes a text file, convert it to CSV and do pandas. This script works perfectly when running in the terminal. Now I want to apply that python script to the file upload in Django and show that file in httpResponse and make available to download it.

python script

import csv
import pandas as pd

df = pd.read_csv('raw_df.txt', delimiter = '\t' , usecols=['Sample','Cohort','Metabolite Name','Intensity'])
df = df[df['Cohort'].str.contains("std")]
df = df.groupby(['Cohort', 'Metabolite Name'])['Intensity'].sum().reset_index()
df = df[['Cohort','Intensity']]
c = 'Cohort'
s = df.set_index([c, df.groupby(c).cumcount() + 2]).Intensity
df =    s.unstack().add_prefix('Intensity').reset_index()
df.to_csv()
print df;

views.py

    from django.shortcuts import render, redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage

from uploads.core.models import Document
from uploads.core.forms import DocumentForm


def home(request):
    documents = Document.objects.all()
    return render(request, 'core/home.html', { 'documents': documents })

def model_form_upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = DocumentForm()
    return render(request, 'core/model_form_upload.html', {
        'form': form
    })

Models.py

class Document(models.Model):
document = models.FileField(upload_to='documents/')

template-upload page

   {% extends 'base.html' %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
  </form>

  <p><a href="{% url 'home' %}">Return to home</a></p>
{% endblock %}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

  1. Wrap your file processing in a method:

    import csv
    import pandas as pd
    
    def process_file(file_handle):
        df = pd.read_csv(file_handle, delimiter = '\t' , usecols['Sample','Cohort','Metabolite Name','Intensity'])
        df = df[df['Cohort'].str.contains("std")]
        df = df.groupby(['Cohort', 'Metabolite Name'])['Intensity'].sum().reset_index()
        df = df[['Cohort','Intensity']]
        c = 'Cohort'
        s = df.set_index([c, df.groupby(c).cumcount() + 2]).Intensity
        df =    s.unstack().add_prefix('Intensity').reset_index()
        return df.to_csv()
    
  2. in your view:

    ... 
    if form.is_valid():
    document = form.save()
    # call to the new method
    csv = process_file(document.document)
    response = HttpResponse(csv, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=result.csv'
    return response
    ...
    
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!