简体   繁体   中英

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

I use the Microsoft Graph tutorial on Django to the authentication process ( https://learn.microsoft.com/en-us/graph/tutorials/python ). Anyone can help me to include that in my code. Thank you

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

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

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

So, instead of newFile.save() , do:

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)

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