简体   繁体   中英

How to Serve User-Uploaded pdf Files in Django?

I am attempting to display user uploaded PDF files in Django. I am successfully able to display images, but not pdf files .

On the landing page, a user is being asked to fill out a Form:

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

I built a model that sets the display_picture to be a simple FileField.

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

    def __str__(self):
        return self.fname

On the view (for both landing page and display of pdf/image, I am sending the user to the details.html after they submit their form

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)


Below is the HTML code for displaying the pdf. When user_pr.display_picture.url is media/filename.pdf, nothing is displayed, yet when user_pr.display_picture.url is media/imagename.jpg an image is displayed. Also worth nothing that the GET Request for media/filename.pdf (user_pr.display_picture.url) receives a 200 code.

  <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>

May be you require to specify the content type.

For pdf content_type='application/pdf'

Try something like below (Not tested..)

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM