Reputation: 4249
I have the following model of an apk, the package_name and sdk_version will be taken by parsing the apk file which the user will upload. I also need to save the path of the uploaded file in my model, that's why I used FilePathField, however I'm not sure it's the correct way to handle the task. I saw some examples where FileField was used, and it got me confused, when do I use which? Another point to make, since a path is just a string, I can save it as Charfield, can't I?
class Apk(models.Model):
package_name = models.CharField(max_length=45, unique=True)
sdk_version = models.CharField(max_length=45, unique=True)
apk_file = models.FilePathField()
To upload the file I used this guide.
views.py:
def upload_apk(request):
handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
return HttpResponse("Upload Successful")
def handle_uploaded_file(file, filename):
if not os.path.exists('policies/upload/'):
os.mkdir('policies/upload/')
with open('policies/upload/' + filename, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
apk_path = "/policies/upload/" + filename
apkf = APK(apk_path)
package_name = apkf.get_package()
sdk_version = apkf.get_androidversion_name()
template.html:
<form id="uploadApkForm" action="{{ request.build_absolute_uri }}uploadApk/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-element" style="border:1px solid black; background:white; padding:2px">
<input type="file" name="file" style="width:100%" required>
</div>
<div style="width:100%;">
<div style="position: absolute;
left: 50%;
bottom: 0px;
transform: translate(-50%, -50%);
margin: 0 auto;">
<input id="uploadBtn" type="submit" value="Ok" class="btn btn-primary" style="width:75px; margin-right:10px" />
<input id="clsBtn" type="button" class="btn btn-primary" value="Cancel" style="width:75px; "/>
</div>
</div>
</form>
I saw different examples where ModelForm was used, and I'm not sure if my way to upload the file is good. Can you please point out what is the best way to upload a file and save it's path in data base?
Upvotes: 0
Views: 196
Reputation: 780
In my opinion, it is probably easiest to use a FileField
. Using a filefield, it will actually save the file at a specific location, as well as allow you to use the file as an object rather just a simple path. With the filefield, it will also give you the ability to access the path.
Upvotes: 1