如何使用表单来更改Django ImageField的文件?

时间:2016-03-29 10:26:50

标签: python django django-forms django-templates

我的 models.py 如下所示:

class Member(models.Model):
    picture = models.ImageField('member profile pic', upload_to = 'member_pictures')

我有以下设置:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

在我的项目 urls.py 中,我将媒体服务器设置如下:

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    # My application url
    url(r'^', include('myapp.urls', namespace='myapp'))

]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在我的应用 urls.py 中,我有以下视图的网址:

from django.conf.urls import url
from myapp import views

urlpatterns = [
    url(
        r'^member/(?P<pk>[0-9]+)/edit/picture$',
        views.member_edit_picture,
        name='member_edit_picture',
    ),
]

现在,我使用一个简单的表单来处理图像上传系统。我的 forms.py 如下所示:

class MemberPictureForm(forms.Form):
    picture = forms.ImageField(
        label='Select a profile picture'
    )

最后,我使用我的视图以下列方式处理表单:

@login_required
def member_edit_picture(request, pk):
    member = Member.objects.get(pk=pk)

    if not request.user == member.user:
        return HttpResponse("You do not have the permission to do that.")

    if request.method == 'POST':
        member_form = MemberPictureForm(request.POST, request.FILES)

        if member_form.is_valid():
            member.picture = request.FILES['picture']
            member.save()
            return redirect('myapp:member_edit_picture', pk=pk)
    else:
        member_form = MemberPictureForm()

    return render(request, 'myapp/member_edit_picture.html', {
        'member' : member,
        'member_form' : member_form,
    })

在我的模板中,我也以正常的方式处理表单

<form method='POST' action=''>
    {% csrf_token %}
    {{member_form|crispy}}
    <input type="submit" class="btn btn-primary" value="Submit" />
</form>

当我选择图像时,文件名会显示在选择按钮旁边。然而,当我单击提交时,视图会重新加载,但是选择按钮字段变为红色,并且表示未选择任何文件。为什么我的表格不起作用?我错过了什么?感谢。

1 个答案:

答案 0 :(得分:1)

来自the file upload docs

  

请注意,request.FILES只会在请求方法为POST并且发布请求的<form>具有属性enctype="multipart/form-data"时才包含数据。否则,request.FILES将为空。