ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 为通用视图CreateView添加自定义验证到字段

2019-09-02 09:55:07  阅读:154  来源: 互联网

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


问题

将自定义验证添加到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().这会产生一些问题,例如我需要手动创建错误消息响应.

解决方法:

为什么不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

标签:python,django,django-models,django-views,django-forms
来源: https://codeday.me/bug/20190902/1790324.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有