python - Django 中的文件上传表单

标签 python django django-uploads

我正在尝试使用 Django 1.5Python 2.7 为我的项目创建一个简单的上传表单。

这是我的File类:

class File(models.Model):
    middleschool = 'MS'
    highschool = 'HS'
    university = 'U'
    blank = '-'

    school_choices = ((middleschool, 'Middle School'), (highschool, 'High school'), (university, 'University'), (blank, 'Not defined'),)

    name = models.CharField(max_length = 30, primary_key=True, blank=False, null=False)
    description = models.CharField(max_length = 140, blank=False, null=False)
    school = models.CharField(max_length = 30, choices = school_choices, default = blank)
    subject = models.ForeignKey(Subject)
    user = models.ForeignKey(User)
    rating = models.DecimalField(max_digits=2, decimal_places=0, default = 0)
    price = models.DecimalField(max_digits=2, decimal_places=1, default = 0, blank=True, null=True)
    file = models.FileField(upload_to= "/file/")

这是表格:

class UploadFileForm(forms.Form):
    middleschool = 'MS'
    highschool = 'HS'
    university = 'U'
    blank = '-'

    school_choices = ((middleschool, 'Middle School'), (highschool, 'High school'), (university, 'University'), (blank, 'Not defined'),)

    name = forms.CharField(max_length = 30, required = True)
    file = forms.FileField()
    description = forms.CharField(max_length = 140, required = False, label='Breif description of the files content')
    school = forms.ChoiceField(choices = school_choices, required=False, label='What level is the material that are you uploading?', initial = blank)
    subject = forms.ModelChoiceField(queryset=Subject.objects.order_by('?'), required=False, label='What subject this file is about?')
    price = forms.IntegerField(required=False)

这是 View :

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = File(file = request.FILE['file'])
            cd = form.cleaned_data
            new_file.name = cd['name']
            new_file.description = cd['description']
            new_file.school = cd['school']
            new_file.subject = cd['subject']
            new_file.price = cd['price']
            new_file.rating = '0.0'
            new_file.user = request.user
            new_file.save()
            form = Search()
            return render(request, 'home.html', {'form': form, 'request': request})
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form, 'request': request})

这是相对的 HTML

{% if request.user.is_authenticated %}
    <form action="" method="post">
    {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Upload">
        <input type="reset" value="Reset">
    </form>
{% else %}
    <p>You must be logged to upload a file</p>
{% endif %}

我的应用程序路径是:C:/Users/User/Desktop/site_is/app_is/,我希望将软管文件保存在以下文件夹中:C:/Users/User/Desktop/site_is/app_is/static/file/。在我的 Setting.py 中我设置:

MEDIA_ROOT = 'C:/Users/User/Desktop/site_is/app_is/static/file/'
MEDIA_URL = '/file/'
STATIC_ROOT = 'C:/Users/User/Desktop/site_is/app_is/static/'
STATIC_URL = '/static/'

问题是:当我选择文件并点击上传按钮时,FileField 会自行清空,并且表单会引发错误,因为该字段是必需的。

我担心我在 Setting.py 中的媒体/静态路径做错了什么,因为 View 语法与 Django docmentation 中的语法相同。但我真的不知道如何解决这个问题。

最佳答案

您应该在 form 标记中指定 enctype 以允许文件上传。

<form action="" method="post" enctype="multipart/form-data">

关于python - Django 中的文件上传表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746002/

相关文章:

django - Heroku:执行查询但没有 postgresql 日志

python - 处理 WSGI 脚本时发生异常 - IOError : failed to write data

python - 从段落中提取热字符之间的多个字符串

python - 我应该将玩家信息存储在服务器还是客户端?

python - 如何在元组列表中使用 numpy.random.choice?

python - 为什么 python openCV 没有按照我期望的方式改变颜色?

python - 获取静态目录时出现404错误

android - 何时进行 GCM 注册

python - Django 模型 : use field from foreign key