为字段添加自定义验证,用于通用视图CreateView

时间:2012-03-17 10:18:58

标签: python django django-models django-forms django-views

问题

将自定义验证添加到Django 1.3中的表单字段,表单由通用视图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通过通用视图从模型创建的。

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

1 个答案:

答案 0 :(得分:5)

为什么不create your modelform

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

然后,您可以使用the form_class attribute

在视图中使用它
class PictureCreateView(CreateView):
    form_class = PictureForm

    # .... snip