我正在尝试为我的项目创建一个简单的上传Django 1.5
表单Python 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)
这是视图:
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
因为视图语法与Django 文档中的相同,但我真的不知道如何解决这个问题。