如何将图像上传到文件夹并将其路径传递给 django 中的视图函数?
How to upload an image to a folder and pass its path to a view function in django?
我想使用 django 模板中的输入文件标签上传图像文件。然后我想做两件事:
1)首先我想将上传的图像存储在我项目的目录中。我想将文件上传到我的应用程序静态目录下的 img 目录中,以便轻松访问它。
2) 其次,我想将这个新存储的图像的文件名发送到一个名为 detect_im()
的视图函数
模板:
<form style="display:inline-block;">
<input type="file" class="form-control-file">
<input type="submit" value="Upload"=>
</form>
查看 views.py
中的函数
def detect_im(request):
haar_file = 'C:\Users\Aayush\ev_manage\face_detector\haarcascade_frontalface_default.xml'
datasets = 'datasets\'
myid = random.randint(1111, 9999)
path = "C:\Users\Aayush\ev_manage\face_detector\" + datasets + str(myid)
if not os.path.isdir(path):
os.mkdir(path)
(width, height) = (130, 100)
face_cascade = cv2.CascadeClassifier(haar_file)
filename = "" //I WANT THE STORED FILE NAME VALUE HERE TO COMPLETE THE PATH FOR FURTHER DETECTION PROCESS BY OPENCV.
image_path = "C:\Users\Aayush\ev_manage\face_detector\static\img\" + filename
count = 1
while count < 30:
im = cv2.imread(image_path)
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (width, height))
cv2.imwrite('% s/% s.png' % (path, count), face_resize)
count += 1
key = cv2.waitKey(10)
if key == 27:
break
return render(request, 'add_dataset.html', {'uid': myid})
最终的流程应该是这样的,用户添加图片并点击上传,然后图片被上传到目录,detect_im() 函数被调用并带有文件名,文件名被用在路径变量中让 opencv 从中检测出人脸。
感谢阅读。请 post 至少添加一些代码的答案,因为我是 python 的新手。
upload an image file using an input file tag from a django template and
store the uploaded image in a directory in my project
尝试使用枕头:
首先,安装包
pip3 install Pillow
接下来,创建一个字段和函数
在你的models.py中:
# models.py
import os
from django.db import models
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext_lazy as _
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return f"(your_dir)/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"
# Do add the date as it prevents the same file name from occuring twice
# the ext is reserved for the file type and don't remove it
class MyExampleClass(models.Model):
...
picture = models.ImageField(_("Picture"), upload_to=upload_to, blank=True, null=True)
然后,创建一个表单来上传图片:
# forms.py
from django import forms
class MyExampleForm(forms.ModelForm):
class Meta:
model = MyExampleClass
fields = ["picture"]
记得在视图中渲染它,你的 url:
# views.py
from django.shortcuts import render, redirect
from .forms import MyExampleForm
def add_image(request):
form = MyExampleForm()
if request.method == "POST":
form = MyExampleForm(data=request.POST, files=request.FILES)
if form.is_valid():
form.save()
return redirect("")
else:
return render(request, "myexamplehtml.html", {"form": form})
# quotes/urls.py
from django.urls import path
from .views import MyExampleView
urlpatterns = [
path('foobar/', add_image, name='myexampleview'),
]
最后,将其添加到您的 HTML 文件中:
{% block content %}
<form method="post" action="your_url" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
{% endblock %}
关于第二部分,我认为您可以像这样访问您的用户变量:
MyExampleModel._meta.get_field('picture')
然后将此代码放入您希望其运行的任何位置
希望这有效!
您可以通过以下方式获取上传文件的路径...
#myImage is your Model
#image is your Model field
myImage.save()
got_url = Image.image.url
print(got_url)
回答link:I am wondering how can we get path of uploaded Image (imageUrl) in views.py file in Django
我想使用 django 模板中的输入文件标签上传图像文件。然后我想做两件事:
1)首先我想将上传的图像存储在我项目的目录中。我想将文件上传到我的应用程序静态目录下的 img 目录中,以便轻松访问它。
2) 其次,我想将这个新存储的图像的文件名发送到一个名为 detect_im()
模板:
<form style="display:inline-block;">
<input type="file" class="form-control-file">
<input type="submit" value="Upload"=>
</form>
查看 views.py
中的函数def detect_im(request):
haar_file = 'C:\Users\Aayush\ev_manage\face_detector\haarcascade_frontalface_default.xml'
datasets = 'datasets\'
myid = random.randint(1111, 9999)
path = "C:\Users\Aayush\ev_manage\face_detector\" + datasets + str(myid)
if not os.path.isdir(path):
os.mkdir(path)
(width, height) = (130, 100)
face_cascade = cv2.CascadeClassifier(haar_file)
filename = "" //I WANT THE STORED FILE NAME VALUE HERE TO COMPLETE THE PATH FOR FURTHER DETECTION PROCESS BY OPENCV.
image_path = "C:\Users\Aayush\ev_manage\face_detector\static\img\" + filename
count = 1
while count < 30:
im = cv2.imread(image_path)
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (width, height))
cv2.imwrite('% s/% s.png' % (path, count), face_resize)
count += 1
key = cv2.waitKey(10)
if key == 27:
break
return render(request, 'add_dataset.html', {'uid': myid})
最终的流程应该是这样的,用户添加图片并点击上传,然后图片被上传到目录,detect_im() 函数被调用并带有文件名,文件名被用在路径变量中让 opencv 从中检测出人脸。
感谢阅读。请 post 至少添加一些代码的答案,因为我是 python 的新手。
upload an image file using an input file tag from a django template and store the uploaded image in a directory in my project
尝试使用枕头:
首先,安装包
pip3 install Pillow
接下来,创建一个字段和函数
在你的models.py中:
# models.py
import os
from django.db import models
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext_lazy as _
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return f"(your_dir)/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"
# Do add the date as it prevents the same file name from occuring twice
# the ext is reserved for the file type and don't remove it
class MyExampleClass(models.Model):
...
picture = models.ImageField(_("Picture"), upload_to=upload_to, blank=True, null=True)
然后,创建一个表单来上传图片:
# forms.py
from django import forms
class MyExampleForm(forms.ModelForm):
class Meta:
model = MyExampleClass
fields = ["picture"]
记得在视图中渲染它,你的 url:
# views.py
from django.shortcuts import render, redirect
from .forms import MyExampleForm
def add_image(request):
form = MyExampleForm()
if request.method == "POST":
form = MyExampleForm(data=request.POST, files=request.FILES)
if form.is_valid():
form.save()
return redirect("")
else:
return render(request, "myexamplehtml.html", {"form": form})
# quotes/urls.py
from django.urls import path
from .views import MyExampleView
urlpatterns = [
path('foobar/', add_image, name='myexampleview'),
]
最后,将其添加到您的 HTML 文件中:
{% block content %}
<form method="post" action="your_url" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
{% endblock %}
关于第二部分,我认为您可以像这样访问您的用户变量:
MyExampleModel._meta.get_field('picture')
然后将此代码放入您希望其运行的任何位置
希望这有效!
您可以通过以下方式获取上传文件的路径...
#myImage is your Model
#image is your Model field
myImage.save()
got_url = Image.image.url
print(got_url)
回答link:I am wondering how can we get path of uploaded Image (imageUrl) in views.py file in Django