Django在文件末尾添加一些奇怪的字符

时间:2019-02-26 13:37:13

标签: python django django-models django-forms

当我将文件提交到django服务器并且文件名存在于目录中时,我遇到了问题。 Django不会覆盖文件,但会在名称末尾添加一些字符。如何添加字符而不是Django。

我的model.py看起来像这样

class UpLoadFile(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      file = models.FileField()
      uploaded_at = models.DateTimeField(default=timezone.now)

      def __str__(self):
          return self.file.name + ' (' + self.user.username + ')'

views.py看起来像这样:

@login_required
def home(request):
    if request.method == 'POST':

        if 'upload_file' in request.POST:
            form = UploadFileForm(request.POST, request.FILES)
            form.instance.user = request.user
            if form.is_valid():
                messages.success(request, 'Datoteka {} je bila uspešno dodana'.format(str(request.FILES["file"])))
                form.save()
                return HttpResponseRedirect('/')

        else:
            messages.error(request, 'Datoteke {} ni bilo mogoče dodati. Preveriti če datoteka vsebuje podatke.'
                           .format(str(request.FILES["file"])))
            return HttpResponseRedirect('/')


    elif request.method == 'GET':
        upload_file = UploadFileForm()
        return render(request, 'update_file/home.html', {'page_title': 'Home', 'upload_form': upload_file})

forms.py看起来像这样:

class UploadFileForm(forms.ModelForm):
    file = forms.FileField(required=True)

    class Meta:
        model = UpLoadFile
        fields = ('file',)

1 个答案:

答案 0 :(得分:0)

Django import requests url_list = ["http://file-examples.com/wp-content/uploads/2017/02/zip_10MB.zip", "http://file-examples.com/wp-content/uploads/2017/02/zip_10MB.zip", "http://file-examples.com/wp-content/uploads/2017/02/zip_10MB.zip", "http://file-examplesc.com/wp-content/uploads/2017/02/zip_10MB.zipdd", "http://file-examples.com/wp-content/uploads/2017/02/zip_10MB.zip"] def download_file(url, total_download_mb): local_filename = url.split('/')[-1] with requests.get(url, stream=True) as r: filesize = int(r.headers["Content-Length"]) / 1024 / 1024 downloaded = 0 with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): if chunk: f.write(chunk) downloaded = (downloaded + len(chunk)) downloaded_mb = downloaded/1024/1024 print("%.2fmb / %.2fmb downloaded." % (downloaded_mb ,filesize)) total_download_mb += downloaded_mb #download is finished could be unpacked .... return total_download_mb def download_url_list(url_list): total_download_mb = 0 failed_urls = [] for i, url in enumerate(url_list): try: total_download_mb = download_file(url, total_download_mb) print("Total download: %.2fmb" % total_download_mb) except: failed_urls.append(url_list[i]) print("failed by file:" + str(i)) print("failed downloads") print(failed_urls) download_url_list(url_list) 类的默认行为是在文件名已经存在时,在文件名的末尾附加一系列随机字符。如果希望控制附加的字符,则可以创建自己的Storage子类并覆盖Storage函数。

一个非常简单的示例,该示例将一组固定的字符追加到名称的末尾(您可能希望适应各种字符):

get_available_name()

然后您可以在模型上指定自定义存储类:

import os
from django.core.files.storage import FileSystemStorage

class MyStorage(FileSystemStorage):

    def get_available_name(self, name, max_length=None):
        if self.exists(name):
            dir_name, file_name = os.path.split(name)
            file_root, file_ext = os.path.splitext(file_name)            

            my_chars = 'abcde'  # The characters you want to append

            name = os.path.join(dir_name, '{}_{}{}'.format(file_root, my_chars, file_ext))
        return name

还值得研究Django get_available_name()的现有代码。