【问题标题】:How to upload an image to a folder and pass its path to a view function in django?如何将图像上传到文件夹并将其路径传递给 django 中的视图函数?
【发布时间】:2020-05-06 09:57:26
【问题描述】:

我想使用 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 的路径变量以检测面对它。

感谢阅读。请发布一个至少添加一些代码的答案,因为我是 python 的新手。

【问题讨论】:

    标签: python django python-3.x file-upload image-upload


    【解决方案1】:

    使用来自 django 模板的输入文件标签上传图像文件,然后 将上传的图片存储在我项目的目录中

    尝试使用枕头:

    首先,安装包

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

    然后把这段代码放到任何你想要它运行的地方

    希望这行得通!

    【讨论】:

    【解决方案2】:

    你可以按照这个来获取上传文件的路径...

    #myImage is your Model
    #image is your Model field
    
    myImage.save()
    got_url = Image.image.url
    
    print(got_url)
    

    回答链接:I am wondering how can we get path of uploaded Image (imageUrl) in views.py file in Django

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2015-10-10
      • 2016-04-02
      • 2019-11-29
      • 2015-01-21
      • 2011-02-26
      • 1970-01-01
      相关资源
      最近更新 更多