我正在Django 1.5
和Python 2.7
开发一个项目。
上传文件Django时会出现错误消息:
SuspiciousOperation at / upload /
尝试访问'\ static \ file \ test_file.txt'被拒绝。
这是追溯:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/upload/
Django Version: 1.5
Python Version: 2.7.6
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'app_is')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Adriano\Desktop\site_is\app_is\views.py" in upload_file
81. new_file.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in insert_query
1673. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
936. for sql, params in self.as_sql():
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in as_sql
894. for obj in self.query.objs
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in pre_save
250. file.save(file.name, file, save=False)
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in save
86. self.name = self.storage.save(name, content)
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in save
47. name = self.get_available_name(name)
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in get_available_name
73. while self.exists(name):
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in exists
243. return os.path.exists(self.path(name))
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in path
259. raise SuspiciousOperation("Attempted access to '%s' denied." % name)
Exception Type: SuspiciousOperation at /upload/
Exception Value: Attempted access to '\static\file\test_file.txt' denied.
这是HTML:
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload">
<input type="reset" value="Reset">
</form>
这是表格:
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.FloatField(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.FILES['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})
这是文件的模型:
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= "/static/file/")
我的应用路径是: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/'
由于我是Django的初学者,我担心我会错过媒体/静态根和/或网址,这会导致错误。
知道如何解决这个问题吗?
答案 0 :(得分:3)
问题在于模型中的这一行:
file = models.FileField(upload_to= "/static/file/")
您正在传递绝对路径,这意味着“将其存储在C:\ static \ file \”中,这不是MEDIA_ROOT
的子目录。您可以将upload_to
参数更改为以C:/Users/User/Desktop/site_is/app_is/static/file/
开头的绝对路径或相对路径:
file = models.FileField(upload_to= ".")