简体   繁体   English

Django:在上传前使用用户名和时间戳重命名文件

[英]Django : Rename a file with the username and the the timestamp before uploading

I am newbee in Django. I have an app where I can upload multiple files.我是Django的新人。我有一个可以上传多个文件的应用程序。 I would like to rename the file by including the username that is authenticated and the timestamp:我想通过包含经过身份验证的用户名和时间戳来重命名文件:

"bild.png" should become "bild_John_Bown_202204055.png" “bild.png”应该变成“bild_John_Bown_202204055.png”

I use the Microsoft Graph tutorial on Django to the authentication process ( https://learn.microsoft.com/en-us/graph/tutorials/python ).我使用 Django 上的 Microsoft Graph 教程进行身份验证过程 ( https://learn.microsoft.com/en-us/graph/tutorials/python )。 Anyone can help me to include that in my code.任何人都可以帮助我将其包含在我的代码中。 Thank you谢谢

models.py模型.py

from django.db import models

class UploadFiles(models.Model):
    
    documents = models.FileField(upload_to='document/', blank=True, null=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)

forms.py forms.py

from django import forms
from django.forms import ClearableFileInput
from .models import UploadFiles

class FilesForm(forms.ModelForm):
    class Meta:
        model = UploadFiles
        fields = ['documents']
        widgets = {'documents': ClearableFileInput(attrs={'multiple': True}),}

views.py视图.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from base.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token
from base.login_helper import *
from django.core.files.storage import FileSystemStorage

from os import listdir
from os.path import isfile, join, getmtime
from django.conf import settings
from base.forms import FilesForm
from base.models import UploadFiles


def home(request):
    context = initialize_context(request)

    return render(request, 'home.html', context)

def initialize_context(request):
    context = {}

    # Check for any errors in the session
    error = request.session.pop('flash_error', None)

    if error != None:
        context['errors'] = []
        context['errors'].append(error)

    # Check for user in the session
    context['user'] = request.session.get('user', {'is_authenticated': False})

    return context

def sign_in(request):

    # Get the sign-in flow
    flow = get_sign_in_flow()
    # Save the expected flow so we can use it in the callback
    try:
        request.session['auth_flow'] = flow
    except Exception as e:
        print(e)
    # Redirect to the Azure sign-in page
    return HttpResponseRedirect(flow['auth_uri'])

def callback(request):
    # Make the token request
    result = get_token_from_code(request)

    #Get the user's profile
    user = get_user(result['access_token'])

    # Store user
    store_user(request, user)
    return HttpResponseRedirect(reverse('home'))

def sign_out(request):
    # Clear out the user and token
    remove_user_and_token(request)

    return HttpResponseRedirect(reverse('home'))

####################################################################
#                            UPLOAD
####################################################################


def upload(request):
    
    context = initialize_context(request)
    user = request.session.get('user').get('name')

    print(user)

    if request.method == 'POST':
        form = FilesForm(request.POST, request.FILES)
        files = request.FILES.getlist('documents')

        if form.is_valid():
            
            for f in files :
                newfile = UploadFiles(documents=f)
                newfile.save()
    else:
        form = FilesForm()

    # Load files for the list page
    files = UploadFiles.objects.all()

    context['files'] = files
    context['form'] = form
    return render(request, 'base/upload.html', context)

Django docs explain it well: https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/#basic-file-uploads Django 文档解释得很好: https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/#basic-file-uploads

So, instead of newFile.save() , do:所以,而不是newFile.save() ,做:

from datetime import datetime

filename = f'{newFile.filename}_{user.username}_{datetime.now().strftime("%Y%m%d)"}'
with open(filename, 'wb+') as destination:
        for chunk in newFile.chunks():
            destination.write(chunk)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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