【问题标题】:How to Serve User-Uploaded pdf Files in Django?如何在 Django 中提供用户上传的 pdf 文件?
【发布时间】:2020-07-15 05:49:02
【问题描述】:

我正在尝试在 Django 中显示用户上传的 PDF 文件。我能够成功显示图像,但不是 pdf 文件

在登录页面上,要求用户填写表单:

class Profile_Form(forms.ModelForm):
    class Meta:
        model = User_Profile
        fields = [
        'fname',
        'lname',
        'technologies',
        'email',
        'display_picture'
        ]

我构建了一个模型,将 display_picture 设置为一个简单的 FileField。

class User_Profile(models.Model):
    display_picture = models.FileField()

    def __str__(self):
        return self.fname

在视图上(对于 pdf/图像的登陆页面和显示,我在用户提交表单后将其发送到 details.html

IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg', 'pdf']

def create_profile(request):

    # Create Form
    form = Profile_Form()

    # If Request is a POST, User needs to be Directed Somwehwere
    if request.method == 'POST':

        # Form Information is extracted from Forms.py
        form = Profile_Form(request.POST, request.FILES)
        if form.is_valid():
            user_pr = form.save(commit=False)
            user_pr.display_picture = request.FILES['display_picture']
            File_Upload_Name = str(request.FILES['display_picture'])
            print("File Name:", File_Upload_Name)

            BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            print("Base Dir: ", BASE_DIR)

            MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
            print("Media Root: ", MEDIA_ROOT)

            # Define Invoice Path
            invoice_path = File_Upload_Name
            user_pr.invoice_path = invoice_path

            # Copy File
            # copyfile("../media/" + user_pr.invoice_path, "../static/" + user_pr.invoice_path)


            print("Invoice Path: ", user_pr.invoice_path)

            # Grab the File Type (Should be ZIP)
            file_type = user_pr.display_picture.url.split('.')[-1]
            file_type = file_type.lower()

            # Confirm the File Type is Correcr
            if file_type not in IMAGE_FILE_TYPES:

                #If not, send user to the Error Page
                return render(request, 'profile_maker/error.html')

            #
            user_pr.save()

            # If file_type is correct and User Performs a POST, return request,
            # Details HTML, and User_PR Dictionary
            return render(request, 'profile_maker/details.html',
                          {'user_pr': user_pr})

    context = {"form": form, }
    return render(request, 'profile_maker/create.html', context)


以下是显示 pdf 的 HTML 代码。当 user_pr.display_picture.url 为 media/filename.pdf 时,不显示任何内容,但当 user_pr.display_picture.url 为 media/imagename.jpg 时,显示图像。对 media/filename.pdf (user_pr.display_picture.url) 的 GET 请求收到 200 代码也毫无价值。

  <p>Document being Analyzed: {{user_pr.invoice_path}}</p>
    <embed src="{{user_pr.display_picture.url}}" width="800px" height="2100px" />
    <img src="{{user_pr.display_picture.url}}" width="800px" height="2100px" />

    <embed src="{% static user_pr.invoice_path %}" width="800px" height="2100px" />
  <p>

【问题讨论】:

    标签: python django pdf


    【解决方案1】:

    您可能需要指定内容类型。

    对于 pdf content_type='application/pdf'

    试试下面的方法(未测试..)

    if file_type == 'pdf':
        return render(request, 'profile_maker/details.html',{'user_pr': user_pr},content_type='application/pdf')
    else:
        return render(request, 'profile_maker/details.html',{'user_pr': user_pr})
    

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 2014-07-11
      • 2013-03-20
      • 1970-01-01
      • 2015-10-23
      • 2018-02-27
      • 2016-04-04
      • 2016-10-22
      • 1970-01-01
      相关资源
      最近更新 更多