检查没有表单的ImageField

时间:2013-07-02 15:07:05

标签: python django

新手Django问题。我在模型上有一个ImageField,我正在上传文件。上传工作正常,但我上传的文件不是图像时我没有得到ValidationErrors。这显然对安全性有害。 full_clean适用于我的URLField和EmailField,但不适用于ImageField。

我模型中的内容摘要:

class Thing(models.Model):
    name = models.CharField(max_length=60, unique=True)
    email = models.EmailField(max_length=254)
    home = models.URLField()
    image = models.ImageField(upload_to=uploader, blank=True, null=True)
    admins = models.ManyToManyField(User)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Thing, self).save(*args, **kwargs)

我的观点和测试中发生的事情摘要:

from django.core.exceptions import ValidationError
from django.test.client import Client

#In views.py
#This is the view for the URL things/[id]
#Modifies an existing model to upload an image to it

def thing(request, thing_id):
    try:
        thing = Thing.objects.get(pk=int(thing_id))
    except:
        raise Http404
    if request.method == 'POST':
        thing.image = request.FILES.get('image')
        try:
            thing.save()
        except ValidationError as e:
            return HttpResponseBadRequest("Error message here")
        return HttpResponse(status=201)



#In tests.py
#This should not work; 'tests.py' is not an image

with open('myapp/tests.py') as f:
    response = Client().post('/things/1', {'image': f})
    print response.content, response.status_code

    #I get that the HTTP status code = 201, not = 400.

我已经找到了很多关于如何使用表单执行此操作的信息,但我不想使用表单。我正在创建一个REST API / Web服务,并且不需要在任何地方将模板嵌入到模板中,因此表单看起来像是不必要的工作。

Django ImageField validation (is it sufficient)?介绍了ImageField验证的工作原理,但不包括我如何实现它。

感谢您的建议!

0 个答案:

没有答案
相关问题