Need a minimum Django file upload sample [Close]

Posted by tdelobe on Tue, 07 Jan 2020 05:19:02 +0100

As a novice to Django, it is difficult for me to make an upload application in Django 1.3.I can't find any recent examples/snippets.Can someone publish a minimum but complete (model, view, template) sample code to do this?

#1st floor

I must say I find the documentation on django confusing.Also for the simplest example, why mention the form?An example of what I do in views.py is: -

for key, file in request.FILES.items():
    path = file.name
    dest = open(path, 'w')
    if file.multiple_chunks:
        for c in file.chunks():
            dest.write(c)
    else:
        dest.write(file.read())
    dest.close()

The html file looks like the following code, although this example uploads only one file, and the code used to save the file can handle many: -

<form action="/upload_file/" method="post" enctype="multipart/form-data">{% csrf_token %}
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

These examples are not my code; they were derived from two other examples I found.I'm a relative starter at django, so I probably missed some key points.

#2nd floor

Here it can help you: create a file field in models.py

To upload a file (in admin.py):

def save_model(self, request, obj, form, change):
    url = "http://img.youtube.com/vi/%s/hqdefault.jpg" %(obj.video)
    url = str(url)

    if url:
        temp_img = NamedTemporaryFile(delete=True)
        temp_img.write(urllib2.urlopen(url).read())
        temp_img.flush()
        filename_img = urlparse(url).path.split('/')[-1]
        obj.image.save(filename_img,File(temp_img)

And use this field in the template.

#3rd floor

I encountered a similar problem and was resolved by Django administering the site.

# models
class Document(models.Model):
    docfile = models.FileField(upload_to='documents/Temp/%Y/%m/%d')

    def doc_name(self):
        return self.docfile.name.split('/')[-1] # only the name, not full path

# admin
from myapp.models import Document
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('doc_name',)
admin.site.register(Document, DocumentAdmin)

#4th floor

demonstration edition

To update Answer by AkseliPal n .See github repo , and Django 2 compatible

Minimum Django file upload example

1. Create a django project

Run startproject:

$ django-admin.py startproject sample

Now create a folder (sample):

sample/
  manage.py
  sample/
    __init__.py
    settings.py
    urls.py
    wsgi.py 

2. Create an application

Create an application:

$ cd sample
$ python manage.py startapp uploader

Now you will create a folder (uploader) that contains the following files:

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

Add'uploader.apps.UploaderConfig'to INSTALLED_APPS at sample/settings.py and add MEDIA_ROOT and MEDIA_URL, that is:

INSTALLED_APPS = [
    ...<other apps>...
    'uploader.apps.UploaderConfig',
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

Add in sample/urls.py:

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.home, name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

Update uploader/models.py:

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.FileField(upload_to="images/")    
    upload_date=models.DateTimeField(auto_now_add =True)

# FileUpload form class.
class UploadForm(ModelForm):
    class Meta:
        model = Upload
        fields = ('pic',)

6. Update views.py

Update uploader/views.py:

from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)       
        if img.is_valid():
            img.save()  
            return HttpResponseRedirect(reverse('imageupload'))
    else:
        img=UploadForm()
    images=Upload.objects.all().order_by('-upload_date')
    return render(request,'home.html',{'form':img,'images':images})

7. Create Templates

Create a folder template in the folder uploader, and then create a file home.html, sample/uploader/templates/home.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>picture</h1>
    <form action="#" method="post" enctype="multipart/form-data">
        {% csrf_token %} {{form}} 
        <input type="submit" value="Upload" />
    </form>
    {% for img in images %}
        {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
        ({{img.upload_date}})<hr />
    {% endfor %}
</div>

8. Synchronize databases

Synchronize the database and run the server:

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

Visit http://localhost.com:8000

#5th floor

I have similar requirements.Most examples on the network require creating models and forms that I don't want to use.This is my final code.

if request.method == 'POST':
    file1 = request.FILES['file']
    contentOfFile = file1.read()
    if file1:
        return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})

In the uploaded HTML, I wrote:

{% block content %}
    <h1>File content</h1>
    <form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    </form>
    {% endblock %}

Here is the HTML that displays the contents of the file:

{% block content %}
    <h3>File uploaded successfully</h3>
    {{file.name}}
    </br>content = {{contentOfFile}}
{% endblock %}

Topics: Django Python github Database