简体   繁体   中英

DJANGO - 404 media when debug is FALSE

I've a trouble with django and I don't know how to fix it.

I use DJANGO 3.2.8 and Python 3.7.12

I code an app that allow a user to upload some file into my DB and when an admin are login he can select an user and clic on ID then it's display the user's ID. When I turn DEBUG = True, everything is ok but when I turn DEBUG = False, I've an 404 error when I try to display the user's ID and I don't know how to fix, I try many thing but nothing work (I use collectstatic for the CSS and it's work when DEBUG = FALSE I've got all my pictures...)

My ID are save in media folder.

Setting

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) 

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') 
STATIC_URL = 'staticfiles/'

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

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

Model

def path_and_rename(path, prefix):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        project = "pid_%s" % (instance.name,)
        # get filename
        if instance.pk:
            complaint_id = "cid_%s" % (uuid.uuid4().hex,)
            filename = '{}.{}.{}.{}'.format(prefix, project, complaint_id, ext)
        else:
            # set filename as random string
            random_id = "rid_%s" % (uuid.uuid4().hex,)
            filename = '{}.{}.{}.{}'.format(prefix, project, random_id, ext)
            # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper


class Company(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    id_card = models.FileField(upload_to=path_and_rename("id_card/", 'id_card'), null=True)

Template

<div>
ID : <a href="{{ companys.id_card.url }}">click here</a>
</div>

Thanks !

I finally find a solution.

I create a sub-domain name media.mywebsite.com

Then I update my settings.py

 MEDIA_ROOT = "/home/USER/public_html/media.mywebsite.com/"

 MEDIA_URL = "https://media.mywebsite.com/"

And it's work ! Maybe not the best way but it's work

Thanks

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