user2251164
user2251164

Reputation: 167

Download Files in Django

I need some help understanding how to download files from my django site to a users machine. I have already created a fairly basic way to upload the files. The files are then an instance of a class and are saved in my "media" folder. What I need help with is how to serve the files. I want the user to be able to visit a page and click on the files they want to download. For some reason I can't find any resources on how to do this. Here are my files at this point

urls.py

    url(r'^admin/', include(admin.site.urls)),
    url(r'^upload/', views.upload),
    url(r'^download/', views.download),
    url(r'^success/', views.success),
)

if settings.DEBUG:
    urlpatterns = patterns('',
                           url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
                           ) + urlpatterns

models.py

class WorkSheet(models.Model):
    worksheet_name = models.CharField(max_length= 150, default = '')
    creator = models.ForeignKey(User, default = True)
    worksheet_file = models.FileField(upload_to = 'worksheets', default = True)
    number_of_stars = models.PositiveIntegerField(default = 0)
    category = models.CharField(max_length = 100, default = '')


class UploadWorkSheetForm(ModelForm):
    class Meta:
        model = WorkSheet
        exclude = ('number_of_stars',
                   'creator',)

views.py

def upload(request):
    if request.method == 'POST':
        form = UploadWorkSheetForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return http.HttpResponseRedirect('/success/')
    else:
        form = UploadWorkSheetForm()
    return render(request, 'upload.html', {'form': form})
def download(request):
    return render_to_response('download.html')
def success(request):
    return render_to_response('upload_success.html')

So basically I want the user to visite www.mysite.com/download and be able to download a file. Thank you!!

. . . . . . . . .

Also, is it a problem that my upload file view does not have a handler like this?

def handle_uploaded_file(file,path=''):
    filename = file._get_name()
    destination_file = open('%s/%s' % (settings.MEDIA_ROOT, str(path) + str(filename)), 'wb+')
    for chunk in file.chunks():
        destination_file.write(chunk)
    destination_file.close()

Upvotes: 0

Views: 3187

Answers (1)

Milind
Milind

Reputation: 590

In your download view, you are just rendering a download.html, but you are not sending any contexts to it. I would may be send a queryset of worksheets,(Worksheet.objects.all()) as a context to the template. And in the template, do something like

{% for worksheet in worksheets %}

{{ worksheet.worksheet_file.url }}

{% endfor %}

Then you would have all the file urls present in your WorkSheet.objects.all() query.

If possible I would handle all the upload logic in the models file itself, something like this

Upvotes: 2

Related Questions