简体   繁体   中英

AWS S3: image is uploading to bucket but file is not showing in heroku Django

Image is uploading to bucket, but it is not showing in the app when it runs. Please help

here Iam using Employee.objects.all() function to fetch the details from database. Please have a look on it and please help me

site adress is : https://mttemployee.herokuapp.com

you can test it using, user name: first and emp Id: 1

please help me fast

settings.py file

import os
import django_heroku

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')


SECRET_KEY = '=^tpe+kln3xg-_kclfay62+4l6c@_l%fj_^k@h0xc5%(0cp^h9'

DEBUG = True

ALLOWED_HOSTS = ['mttemployee.herokuapp.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'manager',
    'storages'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'empmanagement.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'empmanagement.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'empmanage',
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'USER': 'postgres',
        'PASSWORD': '1234',
        'HOST': 'localhost',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [

    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

AWS_ACCESS_KEY_ID = 'xyz'
AWS_SECRET_ACCESS_KEY = 'yxz'
AWS_STORAGE_BUCKET_NAME = 'empmanagementheroku'

AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    STATIC_DIR,
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticsfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Activate Django-Heroku.
django_heroku.settings(locals())

models.py file

from django.db import models

# Create your models here.

class Employee(models.Model):

    first_name  = models.CharField(default="", max_length=50)
    last_name   = models.CharField(default="", max_length=50)
    username    = models.CharField(default="", max_length=50)
    empid       = models.CharField(default="" ,max_length=50)
    dob         = models.DateField(max_length=8)
    address     = models.TextField()
    doj         = models.DateField(max_length=8)
    photo       = models.ImageField(upload_to = 'pics', default = 'pic/default.png')

views.py file

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.models import User, auth
from manager.models import Employee
# Create your views here.


def login(request):
    if(request.method == 'POST'):
        username = request.POST['username']
        empid = request.POST['empid']  
        userdetails = Employee.objects.all()

        for userdetail in userdetails:
            if (userdetail.username == username and userdetail.empid == empid):
                f = 1
                return render(request, 'accounts/details.html',{'userdetail': userdetail})
            else:
                f=0    
        if(f!=1):
            flag = "Invalid Credentials"
            return render(request, 'manager/index.html',{'flag': flag})

    else:
        return render(request,'manager/index.html')

def back(request):
    return render(request, 'manager/index.html')

details.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="{% static 'mystyle.css'%}">
  </head>
  <body>
   <div class="formclass">
    <h1>Details </h1> <br>

    <div class="tablestyle">
     <table align=center>
              <tr><td>Photo : </td><td><img src="{{userdetail.photo.url}}" width=100 height=100 alt=""></td></tr>
              <tr><td>Name  : </td> <td>{{userdetail.first_name}} {{userdetail.last_name}}</td></tr>
              <tr><td>Date of Birth :</td><td>{{userdetail.dob}}</td></tr>
              <tr><td>Address : </td><td>{{userdetail.address}}</td></tr>

              <tr><td>Date Joined : </td><td>{{userdetail.doj}}</td></tr>  
              </table>   
              <br>
    </div> 


              <form action='back' method='post'>
               {% csrf_token %}

              <button type="submit" name="button">Back</button>

      </form>
      <br>
      </div>
  </body>
</html>

If you don't need to use presigned access then you can just update the S3 Bucket policy to make all the files public. All a policy like this or append the statement to your existing policy.

{
  "Id": "Policy1564661477612",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1564661472973",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": "*",
      "Principal": "*"
    }
  ]
}

And in this case you don't need to pass parameters like AWSAccessKeyId=... in the URL.

Otherwise, if you need to have a presigned file access, then upload the file following this guide https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html but keep in mind the file URL will be available for a limited time.

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