Django删除文件

时间:2017-02-12 17:39:52

标签: python django

我有以下模板,允许我上传文件,并在下方显示带有删除按钮的图片:

   <div class="col-md-12 col-md-offset-0">
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="col-xs-12 col-md-5 col-md-offset-0">{{ form.document }}</div>
        <div class="col-xs-12 col-md-1 col-md-offset-0"><button type="submit" >Upload</button></div>
    </form>

    {% for image in images %}
    <div class="col-md-1 col-md-offset-0">
        <img style="width: 100%;" src='{{MEDIA_URL}}/{{ username }}/{{image}}'  alt="ID Image"/>
        <div style="text-align: center;"><button type = "button" class = "btn btn-danger btn-sm">Delete</button></div>
    </div>
    <!-- Indicates a dangerous or potentially negative action -->

    {% endfor %}
    </div>

此模板的视图如下:

@login_required
def profile(request, extra_context={}):
    path="media/" + request.user.username + "/" # insert the path to your directory

    if (os.path.isdir(path)):
        num_files = len([f for f in os.listdir(path)
                     if os.path.isfile(os.path.join(path, f))])
        img_list =os.listdir(path)

    else:

        num_files = 0
        img_list = ""

    username = request.user.username


    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect('profile')
    else:
        form = DocumentForm()
        form_address = ProfileFormAddress()
    return render(request, 'meta/profile.html', {
                  'form': form,
                  'images': img_list,
                  'username': username,
                  'num_files': num_files,
                  'form_address': form_address,
                  })

目前,删除按钮不起作用。我觉得我应该为每个按钮创建一个表单,单击该按钮将删除与该按钮关联的文件。如果有人能提供帮助那就太好了。

2 个答案:

答案 0 :(得分:0)

你应该至少有一个表单来处理这个动作。

您可以通过多种方式执行此操作。

  1. 使用HTTP动词<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.adrissa.image.MainActivity"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="snap" app:popupTheme="@style/AppTheme.PopupOverlay"> </android.support.v7.widget.Toolbar> </android.support.design.widget.AppBarLayout> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical"/> <android.support.design.widget.FloatingActionButton android:id="@+id/fabHome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="16dp" android:src="@mipmap/ic_camera" app:backgroundTint="@color/colorPrimaryDark" app:layout_anchor="@id/container" app:layout_anchorGravity="bottom|right|end"/> </FrameLayout> </android.support.design.widget.CoordinatorLayout> ,即form with method =&#34; DELETE&#34;并将图像名称传递给参数。在代码中正确处理。对很多浏览器表单提交并不能解决这个问题。

  2. 创建不同的视图/配置文件//照片//删除并设置POST并删除。

  3. 不分享代码,因为我觉得你会得到它。

答案 1 :(得分:0)

Bipul让我思考,我决定让每个按钮成为一个表格。如果我用文件名命名每个表单,我可以简单地遍历每个文件,只需删除与按下按钮名称匹配的那个。

模板如下:

        {% for image in images %}
        <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="col-md-1 col-md-offset-0">
                <img style="width: 100%;" src='{{MEDIA_URL}}/{{ username }}/{{image}}'  alt="ID Image"/>
                    <div style="text-align: center;"><button type = "submit" name = "{{image}}" class = "btn btn-danger btn-sm">Delete</button></div>
            </div>
        </form>
        {% endfor %}

查看如下:

@login_required
def profile(request, extra_context={}):
    path="media/" + request.user.username + "/" # insert the path to your directory

    if (os.path.isdir(path)):
        num_files = len([f for f in os.listdir(path)
                     if os.path.isfile(os.path.join(path, f))])
        img_list =os.listdir(path)

    else:

        num_files = 0
        img_list = ""

    username = request.user.username

    if request.method == 'POST' and 'upload' in request.POST:
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect('profile')
    elif request.method == 'POST' and 'address' in request.POST:
        return redirect('profile')
    elif request.method == 'POST':


        for image in img_list:
            if image in request.POST:
                os.remove("media/" + request.user.username + "/" + image)

        return redirect('profile')

    else:
        form = DocumentForm()
        form_address = ProfileFormAddress()

    return render(request, 'meta/profile.html', {
                  'form': form,
                  'images': img_list,
                  'username': username,
                  'num_files': num_files,
                  'form_address': form_address,
                  })