代码之家  ›  专栏  ›  技术社区  ›  Jahmul14

Django文件上载未保存到文件系统

  •  0
  • Jahmul14  · 技术社区  · 7 年前

    设置文件包括:

     BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     MEDIA_URL = '/media/'
     MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    

    模型:

     from django.db import models 
    
     class Document(models.Model):
        description = models.CharField(max_length=255, blank=True)
        document = models.FileField(upload_to='documents/')
        uploaded_at = models.DateTimeField(auto_now_add=True)
    

    形式:

    from django import forms
    from mysite.uploads.models import Document
    
    class DocumentForm(forms.ModelForm):
        class Meta:
            model = Document
            fields = ['description', 'document']
    

     from django.shortcuts import render
     from django.http import HttpResponseRedirect
     from django.core.urlresolvers import reverse
    
     from mysite.uploads.models import Document
     from mysite.uploads.forms import DocumentForm
    
    def model_upload(request):
        if request.method == 'POST':
            form = DocumentForm(request.POST, request.FILES)
            if form.is_valid():
                form.save(commit=True)
                return HttpResponseRedirect(reverse('uploadindex'))
       else:
           form = DocumentForm()
       return render(request, 'uploads/index.html', {
        'form': form
    })
    

    URL:

    from django.conf.urls import url
    
    from mysite.uploads  import views
    
    urlpatterns = [
        url(r'^$', views.model_upload, name='uploadindex'),
    ]
    

     <html>
        <body>
        <form action="{% url "uploadindex" %}" 
           method="post"encytpe="multipart/form-data">
           {% csrf_token %}
           {{ form.as_p }}
           <button type="submit">Upload</button>
        </form>
        </body>
     </html>
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Casey Kinsey    7 年前

    我猜你的文档表单无效,你在 document 字段,但不在模板中呈现任何反馈以表明这一点。

    检查是否已在表单标记上设置了适当的编码。这是通过Django表单处理文件上传时最常见的问题:

    请注意该请求。仅当请求方法为POST并且发布请求的具有属性enctype=“多部分/表单数据”时,文件才会包含数据

    https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#basic-file-uploads

        2
  •  0
  •   Arun V Jose    7 年前
    ...
    if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse('uploadindex'))
    else:
        print form.errors
    ...
    

    它将显示错误,以防 document