gpt4 book ai didi

python - Django SuspiciousOperation at/upload/上传文件时

转载 作者:太空宇宙 更新时间:2023-11-04 01:21:42 25 4
gpt4 key购买 nike

我正在使用 Django 1.5Python 2.7 开发一个项目。上传文件时 Django 引发错误消息:

/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)

这是 View :

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 的初学者,我担心我搞砸了媒体/静态根和/或 url,这会导致出现错误。

知道如何解决这个问题吗?

最佳答案

问题是你模型中的这一行:

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= ".")

关于python - Django SuspiciousOperation at/upload/上传文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20747001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com