Simon TheChain Simon TheChain - 1 year ago 262
Python Question

Django: How to use FilePathField to get file size

I work in a postproduction company, we have our media files on a server. Through the site running on a second server, the user would point to a file, perform some operations (calculating checksums for example) and save the results in the database.

I'm looking for a "best practices" example on how to use FilePathField to get the size of a file. I've read tutorials and searched in the docs, but I'm having trouble putting the pieces together for my needs.

Some relevant code (EDIT: corrected the views, #1 and #3 are printed):

class AssetTest(models.Model):
file_path = models.FilePathField(path=r"", default="")
file_name = models.CharField(max_length=250, default="")
file_size = models.IntegerField(default=0)

def __str__(self):
return self.file_path

class AssetTestForm(forms.ModelForm):

class Meta:
model = AssetTest
fields = ("file_name", "file_size")

def asset_select(request):
if request.method == 'POST':
form = AssetTestForm(request.POST)

if form.is_valid():
form.file_name = request.FILES['file'].name
form.file_size = request.FILES['file'].size
return HttpResponseRedirect('/assetmanage/assets/')


form = AssetTestForm()
return render(request, 'assetmanage/asset_select.html', {'form': form})


{% extends "assetmanage/base.html" %}
{% block title %}Add Asset{% endblock %}

{% block body %}
<div class="container-fluid">

<div class="row">

<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">

<form class="form-horizontal" name="asset_select" action="/assetmanage/asset/test/" method="post" enctype="multipart/form-data">
{% csrf_token %}

<div class="form-group">
<label class="control-label col-sm-2">Select a file:</label>
<input type="file" name="asset_file">

<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>


{% endblock %}

Answer Source

In your FilePathField give the correct path name


cleaned_data of FilePathField will give you the exact path so using that to get the file name and file size of it...

form = AssetTestForm(request.POST)
if form.is_valid():
    temp_file_obj = TemporaryFileUploadHandler(form.cleaned_data['file_path'])
    form.instance.file_size = temp_file_obj.chunk_size
    form.instance.file_name = form.cleaned_data['file_path'].split("/")[-1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download