Django:麻烦uploadind和处理图像(CSRF令牌丢失或不正确)

时间:2015-10-19 14:22:52

标签: django file-upload django-forms csrf image-uploading

我只想尝试使用Django。我尝试制作一个简单的应用程序,允许您上传图像并返回它的像素化版本。 我有两个视图:一个用于显示表单,另一个用于处理图像并返回结果。 问题是“禁止(403)'被提出而不是结果。失败的原因:CSRF令牌丢失或不正确。

urls.py

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

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^result/$', views.pixelate, name='pixelate')
]

views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from .forms import UploadImageForm
from .pixelate import pixelate_image

def index(request):
    form = UploadImageForm()
    return render_to_response('pixelate/index.html', {'form': form})

def pixelate(request):
    form = UploadImageForm(request.POST, request.FILES)
    if form.is_valid():
        response = HttpResponse(content_type='image/png')
        response['Content-Disposition'] = 'filename="image.png"'

        img = pixelate_image(request.FILES['image'])
        response.write(img)
        return response

pixelate.py

from PIL import Image
from io import BytesIO

def pixelate_image(img, pixelSize=9):
    buffer = BytesIO()
    p = Image(buffer)
    image = p.open(img)
    image = image.resize((image.size[0]/pixelSize, image.size[1]/pixelSize), Image.NEAREST)
    image = image.resize((image.size[0]*pixelSize, image.size[1]*pixelSize), Image.NEAREST)
    image.save()
    final_image = buffer.getvalue()
    buffer.close()
    return final_image

forms.py

from django import forms

class UploadImageForm(forms.Form):
    image = forms.ImageField()

的index.html

<form action="{% url 'pixelate:pixelate' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

1 个答案:

答案 0 :(得分:1)

的index.html

<form action="{% url 'pixelate:pixelate' %}" method="post"  enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>