从Django Admin上传pdf文件,以便Public用户可以从前端下载

时间:2017-05-17 09:09:42

标签: python django pdf web-applications django-admin

我正在尝试从django Admin端上传一个<head> <!-- Optional CSS --> <link rel="stylesheet" href="jquery.typeahead.min.css"> <link rel="stylesheet" href="deco.css"> <!-- Required JavaScript --> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="jquery.typeahead.min.js"></script> </head> <body> <var id="result-container" class="result-container"></var> <form id="form-country_v2" name="form-country_v2"> <div class="typeahead__container"> <div class="typeahead__field"> <span class="typeahead__query"> <input class="js-typeahead-country_v2" name="country_v2[query]" placeholder="Search" autocomplete="off" type="search"> </span> <span class="typeahead__button"> <button type="submit"> <i class="typeahead__search-icon"></i> </button> </span> </div> </div> </form> <script> $.typeahead({ input: '.js-typeahead-country_v2', minLength: 2, maxItem: !1, order: "asc", href: "https://en.wikipedia.org/?title={{display}}", template: "{{display}} <small style='color:green;'>{{group}}</small>", source: { country: { ajax: { url: "country_v2.json", path: "data.country" } }, capital: { ajax: { type: "POST", url: "country_v2.json", path: "data.capital", data: { myKey: "myValue" } } } }, callback: { onNavigateAfter: function(node, lis, a, item, query, event) { if (~[38, 40].indexOf(event.keyCode)) { var resultList = node.closest("form").find("ul.typeahead__list"), activeLi = lis.filter("li.active"), offsetTop = activeLi[0] && activeLi[0].offsetTop - (resultList.height() / 2) || 0; resultList.scrollTop(offsetTop); } }, onClickAfter: function(node, a, item, event) { event.preventDefault(); var r = confirm("You will be redirected to:\n" + item.href + "\n\nContinue?"); if (r == true) { window.open(item.href); } $('#result-container').text(''); }, onResult: function(node, query, result, resultCount) { if (query === "") return; var text = ""; if (result.length > 0 && result.length < resultCount) { text = "Showing <strong>" + result.length + "</strong> of <strong>" + resultCount + '</strong> elements matching "' + query + '"'; } else if (result.length > 0) { text = 'Showing <strong>' + result.length + '</strong> elements matching "' + query + '"'; } else { text = 'No results matching "' + query + '"'; } $('#result-container').html(text); }, onMouseEnter: function(node, a, item, event) { if (item.group === "country") { $(a).append('<span class="flag-chart flag-' + item.display.replace(' ', '-').toLowerCase() + '"></span>') } }, onMouseLeave: function(node, a, item, event) { $(a).find('.flag-chart').remove(); } } }); </script> </body> </html> 文件,这样用户可以在网站上注册后从前端下载它是否有任何方法可以执行此任务或任何第三方软件包来执行此任务。

  

注意:我是django的新手

编辑: 项目结构:

pdf

的myproject / settings.py

  ── myproject/
       ├── __init__.py
       ├── settings/
       ├── urls.py
       │__ wsgi.py

  ── myapp/
     └──| __init__.py
        |__ admin.py
        |__ apps.py
        |__ forms.py
        |__ models.py
        |__ tests.py
        |__ urls.py
        |__ views.py

  ── media_cdn/
     ├── static
           |__ media

  ── static/
       ├── css
       └── js
       |__ media

  ── templates
       |__ index.html

的myapp / models.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
    ]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')

的myapp / urls.py

class My_model(models.Model):
    title = models.CharField(max_length=25)
    pdf = models.FileField(upload_to='static/media')


    def __str__(self):
        return self.title

的myapp / admin.py

urlpatterns = [
   url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),

   url(r'^download/(?P<path>.*)$', serve, {'document root': settings.MEDIA_ROOT}),

   ]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

的myapp / views.py

from accounts import models

admin.site.register(models.My_model)

的index.html

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/pdf")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

当我点击前端的链接时,它只会将整个页面下载为<a href="{{ my_Model_instance.pdf.url }}" download>Click here to download PDF</a> 文件

但是,当我对HTML进行硬编码时(以下载url为例)

test123.pdf

下载(但问题是<a href="/static/media/test123.pdf" download>Click here to download PDF</a> 来自my_Model中的django admin上传文件

1 个答案:

答案 0 :(得分:1)

您需要创建一个模型:

class My_model(models.Model):
    pdf = models.FileField(upload_to='special location or name')
来自admin.py的

from django.contrib import admin
from my_app import models

admin.site.register(models.My_model)

您可以像在视图中一样访问它:

<a href="{{ my_Model_instance.pdf.url }}">Click here to download PDF</a>