问题描述
我在 Django 1.5
和 Python 2.7
中开发项目。
上传文件时Django会出现错误消息:
I'm developing a project in Django 1.5
and Python 2.7
.While uploading a file Django raise an error message:
/ 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
我设置:
My app path is: C:/Users/User/Desktop/site_is/app_is/
and I want hose files saved in the folder: C:/Users/User/Desktop/site_is/app_is/static/file/
. In my Setting.py
I set:
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的初学者,我害怕我填补了媒体/静态根和/或url,这导致了错误提出。
Since I'm a beginner in Django i fear that i mssed up the media/static root and/or url and this results in the error raised.
任何想法如何解决这个问题?
Any idea how to solve this?
推荐答案
问题是您的模型中的这一行:
The problem is this line in your models:
file = models.FileField(upload_to= "/static/file/")
绝对路径,这意味着存储在C:\static\file\中,它不是您的 MEDIA_ROOT
的子目录。您可以将 upload_to
参数更改为以 C:/ Users / User / Desktop / site_is / app_is / static / file /
或相对路径:
You are passing an absolute path, which would mean "store this in C:\static\file\", which is not a subdirectory of your MEDIA_ROOT
. You can change the upload_to
parameter either to an absolute path that starts with C:/Users/User/Desktop/site_is/app_is/static/file/
, or a relative path:
file = models.FileField(upload_to= ".")
这篇关于Django SuspiciousOperation在/ upload /上传文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!