Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django从模型中读取文件,[Errno 2]没有这样的文件或目录_Python_Django - Fatal编程技术网

Python Django从模型中读取文件,[Errno 2]没有这样的文件或目录

Python Django从模型中读取文件,[Errno 2]没有这样的文件或目录,python,django,Python,Django,在Django中,我使用模型表单上传下面所示模型中的.stl文件。提交表单后,我看到文件被上传到myproject=>media目录。但是,当从模型中读取上传的文件时,我一直在获取“未找到文件”错误。 我尝试使用绝对路径和相对路径,但都没有成功,非常感谢您的帮助 设置.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') from django.db import models class StlFile(

在Django中,我使用模型表单上传下面所示模型中的.stl文件。提交表单后,我看到文件被上传到myproject=>media目录。但是,当从模型中读取上传的文件时,我一直在获取“未找到文件”错误。 我尝试使用绝对路径和相对路径,但都没有成功,非常感谢您的帮助

设置.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.db import models

class StlFile(models.Model):
    uploaded_file = models.FileField()
    uploaded_at = models.DateTimeField(auto_now_add=True)
    volume = models.FloatField(default=0.0)
from django import forms
from .models import StlFile

class StlForm(forms.ModelForm):
    class Meta:
        model = StlFile
        fields = [
            'uploaded_file'
        ]
import os
from django.shortcuts import render
import numpy as np
from stl import mesh
from .forms import StlForm
from .models import StlFile
# Create your views here.
def model_form_upload(request):
    if request.method == 'POST':
        form = StlForm(request.POST, request.FILES)
        if form.is_valid():
            stl_file = form.save(commit=False) # Read file but Don't save the file yet
            stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter
            stl_file.save()
            # Extract mechanical properties from STL
            stl_path = stl_file.uploaded_file.url
            stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the url
            volume, cog, inertia = stl_mesh.get_mass_properties()            
            return render(request, 'stl_upload/success.html')
    else:
        form = StlForm()
    return render(request, 'stl_upload/upload.html', {'form': form})
model.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.db import models

class StlFile(models.Model):
    uploaded_file = models.FileField()
    uploaded_at = models.DateTimeField(auto_now_add=True)
    volume = models.FloatField(default=0.0)
from django import forms
from .models import StlFile

class StlForm(forms.ModelForm):
    class Meta:
        model = StlFile
        fields = [
            'uploaded_file'
        ]
import os
from django.shortcuts import render
import numpy as np
from stl import mesh
from .forms import StlForm
from .models import StlFile
# Create your views here.
def model_form_upload(request):
    if request.method == 'POST':
        form = StlForm(request.POST, request.FILES)
        if form.is_valid():
            stl_file = form.save(commit=False) # Read file but Don't save the file yet
            stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter
            stl_file.save()
            # Extract mechanical properties from STL
            stl_path = stl_file.uploaded_file.url
            stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the url
            volume, cog, inertia = stl_mesh.get_mass_properties()            
            return render(request, 'stl_upload/success.html')
    else:
        form = StlForm()
    return render(request, 'stl_upload/upload.html', {'form': form})
forms.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.db import models

class StlFile(models.Model):
    uploaded_file = models.FileField()
    uploaded_at = models.DateTimeField(auto_now_add=True)
    volume = models.FloatField(default=0.0)
from django import forms
from .models import StlFile

class StlForm(forms.ModelForm):
    class Meta:
        model = StlFile
        fields = [
            'uploaded_file'
        ]
import os
from django.shortcuts import render
import numpy as np
from stl import mesh
from .forms import StlForm
from .models import StlFile
# Create your views here.
def model_form_upload(request):
    if request.method == 'POST':
        form = StlForm(request.POST, request.FILES)
        if form.is_valid():
            stl_file = form.save(commit=False) # Read file but Don't save the file yet
            stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter
            stl_file.save()
            # Extract mechanical properties from STL
            stl_path = stl_file.uploaded_file.url
            stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the url
            volume, cog, inertia = stl_mesh.get_mass_properties()            
            return render(request, 'stl_upload/success.html')
    else:
        form = StlForm()
    return render(request, 'stl_upload/upload.html', {'form': form})
POST请求后,numpy stl从views.py中的模型读取保存的stl文件

视图.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.db import models

class StlFile(models.Model):
    uploaded_file = models.FileField()
    uploaded_at = models.DateTimeField(auto_now_add=True)
    volume = models.FloatField(default=0.0)
from django import forms
from .models import StlFile

class StlForm(forms.ModelForm):
    class Meta:
        model = StlFile
        fields = [
            'uploaded_file'
        ]
import os
from django.shortcuts import render
import numpy as np
from stl import mesh
from .forms import StlForm
from .models import StlFile
# Create your views here.
def model_form_upload(request):
    if request.method == 'POST':
        form = StlForm(request.POST, request.FILES)
        if form.is_valid():
            stl_file = form.save(commit=False) # Read file but Don't save the file yet
            stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter
            stl_file.save()
            # Extract mechanical properties from STL
            stl_path = stl_file.uploaded_file.url
            stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the url
            volume, cog, inertia = stl_mesh.get_mass_properties()            
            return render(request, 'stl_upload/success.html')
    else:
        form = StlForm()
    return render(request, 'stl_upload/upload.html', {'form': form})
错误 回溯错误

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/stl_upload/

Django Version: 3.1.1
Python Version: 3.6.6
Installed Applications:
['stl_upload',
 'maths',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\olahurikar\Desktop\Misllenious\MOD\Dango_Experiments\django_venv_experiment\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\olahurikar\Desktop\Misllenious\MOD\Dango_Experiments\django_venv_experiment\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\olahurikar\Desktop\Misllenious\MOD\Dango_Experiments\experiment\stl_upload\views.py", line 18, in model_form_upload
    stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the url
  File "C:\Users\olahurikar\Desktop\Misllenious\MOD\Dango_Experiments\django_venv_experiment\lib\site-packages\stl\stl.py", line 328, in from_file
    with open(filename, 'rb') as fh:

Exception Type: FileNotFoundError at /stl_upload/
Exception Value: [Errno 2] No such file or directory: 'C:/media/panther_wH1qGon.stl'

由于,您的媒体文件无法访问。因此,我们将使用设置文件中定义的
MEDIA\u ROOT
。因此:

import os
from django.shortcuts import render
import numpy as np
from stl import mesh
from .forms import StlForm
from .models import StlFile
from pacakge_name.settings import MEDIA_ROOT  # package_name , the folder inside which your settings.py is
# Create your views here.
def model_form_upload(request):
    if request.method == 'POST':
        form = StlForm(request.POST, request.FILES)
        if form.is_valid():
            stl_file = form.save(commit=False) # Read file but Don't save the file yet
            stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter
            stl_file.save()
            # Extract mechanical properties from STL
            stl_path = f"{MEDIA_ROOT}/{Stl_file.uploaded_file.name}"
            stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the url
            volume, cog, inertia = stl_mesh.get_mass_properties()            
            return render(request, 'stl_upload/success.html')
    else:
        form = StlForm()
    return render(request, 'stl_upload/upload.html', {'form': form})
导入操作系统
从django.shortcuts导入渲染
将numpy作为np导入
从stl导入网格
from.forms导入StlForm
从.models导入STL文件
从pacakge_name.settings导入媒体_ROOT#pack_name,您的settings.py所在的文件夹
#在这里创建您的视图。
def型号表格上传(请求):
如果request.method==“POST”:
form=StlForm(request.POST、request.FILES)
如果form.is_有效():
stl_file=form.save(commit=False)#读取文件但不保存文件
stl_file.upload_file=request.FILES['upload_file']#读取模型参数中的文件实例
stl_file.save()文件
#从STL中提取力学特性
stl_path=f“{MEDIA_ROOT}/{stl_file.upload_file.name}”
stl_mesh=mesh.mesh.from_文件(stl_路径)#从url读取保存的文件
体积、中心距、惯性=stl_网格。获取质量_属性()
返回渲染(请求'stl_upload/success.html')
其他:
form=StlForm()

返回render(请求'stl_upload/upload.html',{'form':form})
Hi@Omkar,你的
stl_upload/success.html
看起来怎么样。我正在从事类似的项目,非常感谢您的帮助。谢谢@NirajDPandey,它的工作。我有兴趣了解更多关于你的项目。你可以打电话找我oalahuri@mtu.edu