更改Django中上载图像的文件名

2024-10-06 10:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我如何重命名我的图像文件,以防止重复的文件名。目前我有一个照片列表,可以将文件名上传到数据库,它会自动创建文件夹,并将所选照片保存到我的media文件夹中。我想要的是每个图像文件名必须是唯一的。如果有人能找出我哪里做错了,那就太好了。事先非常感谢

views.py

@login_required(login_url='log_permission')
def scanned_docs_add(request):
    if request.method == 'POST':
        gallery = folder_info.objects.create(
        title = request.POST.get('title'),
        date_upload = datetime.date.today()
    )
    for file in request.FILES.getlist('photos[]'): #imagefile--------
        oas = gallery_photos.objects.create(
            gallery_info_id = gallery.id,
            photos = file,
        )
return JsonResponse({'data': 'success'})

models.py

class folder_info(models.Model):
    title = models.CharField(max_length=50,blank=True, null=True)
    date_upload = models.DateField(null=True, blank=True)
    class Meta:
        db_table = "folder_info"

class gallery_photos(models.Model):
    gallery_info_id = models.IntegerField()
    photos = models.FileField(upload_to='Photos/', unique=True)
    class Meta:
        managed = False
        db_table = 'gallery_photos'

html

  <form id="uploadevent" >
  {% csrf_token %}
   <input type="file" multiple data-bind="fileInput: multiFileData, customFileInput: {                                                                 
      }" accept="image/*" name="photos[]" required="">
  <button type="submit" class="btn btn-outline-primary">Save changes</button>
  </form>

脚本

<script type="text/javascript">
$('#uploadevent').on('submit', function(e){
  $.ajax({
      data        : new FormData(this),
      url         : "{% url 'scanned_docs_add' %}",
      type        : 'POST',
      cache       : false,
      contentType : false,
      processData : false
  })
  .done(function(data){
      var info = data.data;
      if(info){
          $('#uploadevent').modal('toggle');
          toastrOptions();
          toastr.success("Successfully Saved!",{
              timeOut: 1000,
              fadeOut: 1000,
              onHidden: function(){
                  window.location.reload();
              }
          });
          $('#uploadevent').trigger('reset');    
      }
  });

  e.preventDefault();
  });
 </script>

Tags: infoidtrueurldata文件名modelsrequest
1条回答
网友
1楼 · 发布于 2024-10-06 10:26:37

请试一试

from django.db import models
import os


def get_media_path(model, filename):
    class_name = model.__class__.__name__
    code = str(model.id)
    # here you can change the name
    filename = filename # or another thing
    return os.path.join(class_name, code, filename)


class gallery_photos(models.Model):
    gallery_info_id = models.IntegerField()
    # photos = models.FileField(upload_to='Photos/', unique=True)
    photos = models.FileField(upload_to=get_media_path)
    
    class Meta:
        managed = False
        db_table = 'gallery_photos'


请尝试使用camelcase作为类名GalleryPhoto(仅作为一个对象)而不是gallery_photos

相关问题 更多 >