2016-04-03 13 views
7

मैं Django का उपयोग करने के लिए काफी नया हूं और मैं ऐसी वेबसाइट विकसित करने की कोशिश कर रहा हूं जहां उपयोगकर्ता कई एक्सेल फ़ाइलों को अपलोड करने में सक्षम है, फिर इन फ़ाइलों को मीडिया फ़ोल्डर वेबप्रोजेक्ट/प्रोजेक्ट/मीडिया।Django फ़ाइल डाउनलोड करें

def upload(request): 
    if request.POST: 
     form = FileForm(request.POST, request.FILES) 
     if form.is_valid(): 
      form.save() 
      return render_to_response('project/upload_successful.html') 
    else: 
     form = FileForm() 
    args = {} 
    args.update(csrf(request)) 
    args['form'] = form 

    return render_to_response('project/create.html', args) 

दस्तावेज़ तो और कोई अन्य दस्तावेज वे अपलोड कर दिया है, तो आप में क्लिक कर सकते हैं जो के साथ एक सूची में प्रदर्शित होता है यह होगा उनके बारे में बुनियादी जानकारी और excelfile वे अपलोड कर दिया है के नाम प्रदर्शित करता है। यहाँ से मैं फिर से लिंक का उपयोग कर फ़ाइल उत्कृष्टता ही डाउनलोड करने के लिए सक्षम होना चाहते हैं:

<a href="/project/download"> Download Document </a> 

मेरे यूआरएल हैं

urlpatterns = [ 

       url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], 
              template_name="project/project.html")), 
       url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name="project/post.html")), 
       url(r'^upload/$', upload), 
       url(r'^download/(?P<path>.*)$', serve, {'document root': settings.MEDIA_ROOT}), 

      ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

लेकिन मैं त्रुटि, की सेवा मिल() एक अप्रत्याशित कीवर्ड तर्क 'मिला दस्तावेज़ रूट '। क्या कोई इसे ठीक करने के बारे में बता सकता है?

या

के बारे में बताएं कि कैसे मैं अपलोड की गई फ़ाइलों का चयन किया जाना करने के लिए प्राप्त कर सकते हैं और का उपयोग कर प्रस्तुत ऐसे

def download(request): 
    file_name = #get the filename of desired excel file 
    path_to_file = #get the path of desired excel file 
    response = HttpResponse(mimetype='application/force-download') 
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) 
    response['X-Sendfile'] = smart_str(path_to_file) 
    return response 
+1

क्या आप 'सेवा' दृश्य से कोड शामिल कर सकते हैं? – xthestreams

उत्तर

21

आप तर्क दस्तावेज़ _ जड़ में अंडरस्कोर याद किया। लेकिन उत्पादन में serve का उपयोग करना बुरा विचार है। इसके बजाए इस तरह कुछ उपयोग करें:

import os 
from django.conf import settings 
from django.http import HttpResponse 

def download(request, path): 
    file_path = os.path.join(settings.MEDIA_ROOT, path) 
    if os.path.exists(file_path): 
     with open(file_path, 'rb') as fh: 
      response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") 
      response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) 
      return response 
    raise Http404 
+0

बहुत अच्छा काम किया। धन्यवाद – jsm1th

+0

यह मेरे लिए काम आसान है। thx @ सर्गी Gornostaev – gustav

संबंधित मुद्दे