Django 文件上传不起作用:文件未出现在媒体目录或数据库中

问题描述 投票:0回答:1

我正在开发一个 Django 应用程序,用户可以在其中上传与特定主题和提交相关的文件。尽管根据 Django 文档设置了所有内容,但文件在上传后不会出现在指定的媒体目录或数据库中。我正在使用 Django 5.0.4 和 Python 3.10。

模型.py:

class File(models.Model):
    topic = models.ForeignKey(Topic, related_name='files', on_delete=models.CASCADE, null=True)
    submission = models.ForeignKey(Submission, related_name='files', on_delete=models.CASCADE, null=True)
    filename = models.FileField(upload_to='submissions/', null=True)
    upload_date = models.DateTimeField(auto_now_add=True)
    is_accepted = models.BooleanField(default=False)
     
    def __str__(self):
        return f"File: {self.filename.name} for Topic: {self.topic.name}"
    

Forms.py:

class UploadFileForm(ModelForm):
    class Meta:
        model = File
        fields = ('filename',)
  

Views.py:

def upload_file(request, subm_id, topic_id):
    submission = get_object_or_404(Submission, pk=subm_id)
    topic = get_object_or_404(Topic, pk=topic_id)
    form = UploadFileForm()
    context = {'submission':submission, 'topic':topic, 'form': form}
    
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        
        if form.is_valid(): 
            file_instance = form.save(commit=False)
            file_instance.topic = topic
            file_instance.submission = submission
            file_instance.save()
            messages.success(request, 'File succesfully uploaded')
            return redirect('upload_file', subm_id=submission.id, topic_id=topic.id)
        else:
            print(request.FILES)
            messages.error(request, 'No file was uploaded')
            form = UploadFileForm()
    return render(request, 'users/upload_file.html', context=context)

设置.py:

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

模板:

<form method="POST" action="" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="mb-3">
              <label class="form-label" for="{{ form.filename.id_for_label}} "
                >Загрузите файл</label
              >
              {{ form|crispy }}
            </div>
            <input class="btn btn-secondary" type="submit" value="Submit" />
          </form>

什么可能导致此问题以及如何解决它以确保文件正确上传并保存在 Django 中?

python django database sqlite django-file-upload
1个回答
0
投票

以下是可能情况的列表:

  1. 缺少媒体网址

    如果设置.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

  2. 如果您提交文件,表单应具有 enctype="multipart/form-data",例如:

  3. 尝试在视图中打印出一些行(这在许多情况下很有帮助),只是为了看看它是否正常工作或哪里中断。

    def upload_file(请求, subm_id, topic_id): 提交 = get_object_or_404(提交, pk=subm_id) 主题 = get_object_or_404(主题, pk=topic_id) 表单 = 上传文件表单() context = {'submission': 提交, 'topic': 主题, 'form': 表单}

     if request.method == 'POST':
         print("POST request received.")
         print("Files in request:", request.FILES)
         form = UploadFileForm(request.POST, request.FILES)
    
         if form.is_valid():
             print("Form is valid.")
             file_instance = form.save(commit=False)
             file_instance.topic = topic
             file_instance.submission = submission
             file_instance.save()
             print(f"File instance created and saved: {file_instance}")
             messages.success(request, 'File successfully uploaded')
             return redirect('upload_file', subm_id=submission.id, topic_id=topic.id)
         else:
             print("Form is not valid. Errors:", form.errors)
             messages.error(request, 'No file was uploaded or form was invalid.')
             form = UploadFileForm()
    
     print("Rendering the upload file page.")
     return render(request, 'users/upload_file.html', context=context)
    
© www.soinside.com 2019 - 2024. All rights reserved.