dJudge
dJudge

Reputation: 186

Updating model's FileField manually in django views

I have a csv file stored in a model's FileField. I want to drop selected columns from the csv file and update the file stored in the Project's FileField.

I have successfully retrieved the file from the model and stored it into a Pandas DataFrame. Selected columns are successfully dropped from the dataframe BUT failed to UPDATE the file stored in the Project's FileField.

Here is my model:

class Project(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    base_file = models.FileField(upload_to='project-files', default=True)
    date_created = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

Here is the view that suppose to manipulate the file through pandas dataframe:

def PreprocessView(request, **kwargs):
    proj_pk = kwargs.get('pk')

    project = Project.objects.get(id=proj_pk)  
    df      = pd.read_csv(project.base_file)
    n_cols  = df.keys

    context ={}
    context['df']     = df
    context['n_cols'] = n_cols

    if request.method == 'POST':       
        checked_values = request.POST.getlist(u'predictors')
        str_check_values = ', '.join(checked_values)
        df.drop(columns=checked_values, inplace=True)
        new_df = df.to_csv(project.base_file.name)
        project.base_file = new_df
        project.save()

        messages.success(request, f'{str_check_values} has been successfuly removed!')

    return render(request, 'projects/preprocess/preprocess.html', context)

The following lines returns an error and failed to update the File in the database.

        new_df = df.to_csv(project.base_file.name)
        project.base_file = new_df
        project.save()

Upvotes: 5

Views: 1334

Answers (2)

Nafees Anwar
Nafees Anwar

Reputation: 6598

You have to create a file object and then attach it to model. Like this

from django.core.files.base import ContentFile


if request.method == 'POST':       
    checked_values = request.POST.getlist(u'predictors')
    str_check_values = ', '.join(checked_values)
    df.drop(columns=checked_values, inplace=True)
    new_df = df.to_csv()

    updated_file = ContentFile(new_df)
    updated_file.name = "filename.csv"

    project.base_file = updated_file
    project.save()

Upvotes: 3

dirkgroten
dirkgroten

Reputation: 20682

DataFrame.to_csv() returns None if you give it a file path to save to. So new_df is None.

You don't need to do anything after you did df.to_csv(project.file.name), the file is already changed.

Upvotes: 0

Related Questions