向字段添加自定义验证,用于通用视图 CreateView [英] Adding custom validation to a field, for the generic view CreateView

查看:21
本文介绍了向字段添加自定义验证,用于通用视图 CreateView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Django 1.3 中为表单字段添加自定义验证,表单由通用视图 CreateView 创建.

Add custom validation to a form field in Django 1.3, the form is created by the generic view CreateView.

class Picture(models.Model):
    file = models.ImageField(upload_to=get_image_path)
    filename = models.CharField(max_length=50, blank=True)
    user = models.ForeignKey(User, editable=False)
    upload_date = models.DateTimeField(auto_now_add=True,editable=False)

通用视图 CreateView,稍作修改

class PictureCreateView(CreateView):
    model = Picture

    def clean_file(self,form):
        if image:
            if image._size > settings.MAX_IMAGE_SIZE:
                raise ValidationError("Image file too large ( > 20mb )")
        else:
             raise ValidationError("Couldn't read uploaded image")

    def get_form(self, form_class):
        form = super(PictureCreateView, self).get_form(form_class)
        form.instance.user = self.request.user
        return form

    def form_invalid(self, form):
        ...omitted none important code...
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

    # Called when we're sure all fields in the form are valid
    def form_valid(self, form):
        ...omitted none important code...
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

我的问题是:在达到 form_valid() 之前,如何对文件字段进行自定义验证?

简而言之,到目前为止我所做的

根据此处的文档 - https://docs.djangoproject.com/en/dev/ref/forms/validation/我应该能够覆盖文件字段表单验证器,我正在尝试使用 clean_file()表单子类中的 clean_() 方法 - 其中替换为表单字段属性的名称."如果我手动创建表单,这会很容易,但它是由 Django 通过通用视图从模型创建的.

My question is: How can I do custom validation on the file field, before form_valid() is reached?

In short, what I've done so far

According to the documentation here - https://docs.djangoproject.com/en/dev/ref/forms/validation/ I should be able to override the file fields form validator, which I'm trying to do with clean_file() "The clean_() method in a form subclass - where is replaced with the name of the form field attribute. " This would have been easy if I had created the form manually, but it's created by Django from the model by the generic view.

我目前的解决方案,这是一个丑陋的黑客:你可以看到我已经覆盖了 form_valid() 和 form_invalid(),在 form_valid() 我现在调用 clean_file()如果这是一个错误,我会调用 form_invalid().这会产生一些问题,例如我需要手动创建错误消息响应.

My current solution, which is a ugly hack: You can see that I've overridden form_valid() and form_invalid(), in form_valid() I now call clean_file() and if it's a error I call form_invalid(). This creates a few problems, for example I need to create the error message response manually.

推荐答案

为什么不 创建您的模型 ?

from django import forms

class PictureForm(forms.ModelForm):
    def clean_file(self,form):
        if image:
            if image._size > settings.MAX_IMAGE_SIZE:
                raise ValidationError("Image file too large ( > 20mb )")
        else:
            raise ValidationError("Couldn't read uploaded image")

    class Meta:
        model = Picture

然后你可以在你的视图中使用它 form_class 属性:

Then you could use it in your view with the form_class attribute:

class PictureCreateView(CreateView):
    form_class = PictureForm

    # .... snip

这篇关于向字段添加自定义验证,用于通用视图 CreateView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆