简体   繁体   中英

How to upload and view images in django

models.py

 class FileUpload(models.Model):
    File_Name = models.CharField(max_length=255, blank=True)
    File_path = models.FileField(upload_to='')
    Description = models.CharField(max_length=255, blank=True)
    Upload_Date = models.DateTimeField(auto_now_add=True)

forms.py

 class FileUploadForm(forms.Form):
   class Meta:
      model = FileUpload

      File_Name = forms.CharField(label="File Name",max_length=255)  
      Description = forms.CharField(label="Description", max_length=255) 

I'm new in Django.I need help. How to upload images in the database and view those images? Thanks in advance!

here paths are stored in database and images are stored in a folder. But I don't need that. I want to save images and path to the database and I need to view that image. Please help!

views.py:

def uploadfile(request):
   print('inside upload logic')
   if request.method == 'POST':
      form = FileUploadForm(request.POST, request.FILES)
      if form.is_valid():
        # ImageUpload(request.FILES['File_Name'])  
         myfile = request.FILES['File_Name']

         fs = FileSystemStorage()
         filename = fs.save(myfile.name, myfile)
         uploaded_file_url = fs.url(filename)
         newdoc = FileUpload(File_Name=myfile.name, File_path=uploaded_file_url,  Description=request.POST['Description'])
         newdoc.save()
         #return HttpResponse("File uploaded successfuly")  
         return render(request, 'Login/fileupload.html')   
   else:
      form = FileUploadForm()
      return render(request, 'Login/fileupload.html', {
      'form': form
   }) 

You normally shouldn't store the image data in your database. If you need to upload and store images, use the ImageField or FileField and follow the instructions from the docs to save the image. The only thing you need to do is:

form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
    uploaded_file = FileUpload(
        File_path=request.FILES['File_path'],  # or whatever you've called the file input
        File_name=form.cleaned_data['File_Name'],
        Description=form.cleaned_data['Description'])
    uploaded_file.save()

It would be easier to use a ModelForm in your case, then you only need to save the form:

if form.is_valid():
    form.save()

This will automatically save the file in the correct way. No need to do the saving manually like you are doing.

To view the image is as simple as this:

file_upload = FileUpload.objects.get(id=34)
file_url = file_upload.File_path.url  # url relative to `MEDIA_ROOT`

# or in a template
{% load static %}
{% get_media_prefix %}{{ file_upload.File_path.url }}

If you really need to store the images as binary blobs to your database (but beware that it almost never makes sense to do so), use Django's BinaryField , as described here .

This also means you will have to handle transforming the image back and forth from a binary blob to a proper image file. Consider also storing the content type (image/jpg or image/png or image/webp) since you will need that to properly re-create the file.

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