Django Forms Validation消息未显示 [英] Django Forms Validation message not showing

查看:44
本文介绍了Django Forms Validation消息未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试限制可以在表单中上传的文件类型,大小和扩展名.该功能似乎起作用,但是未显示验证错误消息.我意识到 if file._size>4 * 1024 * 1024 可能不是最好的方法-但我稍后会处理.

I'm trying to restrict file type, size and extension that can be uploaded in a form. The functionality seems to work, but the validation error messages are not showing. I realize that if file._size > 4*1024*1024 is probably not the best way - but I'll deal with that later.

这是表格.py:

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url', 'product_file']
        labels = {
            'name': 'Product Name',
            'url': 'Product URL',
            'product_type': 'Product Type',
            'description': 'Product Description',
            'image': 'Product Image',
            'image_url': 'Product Image URL',
            'price': 'Product Price',
            'product_file': 'Product Zip File',
        }
        widgets = {
            'description': Textarea(attrs={'rows': 5}),
        }

    def clean(self):
        file = self.cleaned_data.get('product_file')

        if file:
            if file._size > 4*1024*1024:
                raise ValidationError("Zip file is too large ( > 4mb )")
            if not file.content-type in ["zip"]:
                raise ValidationError("Content-Type is not Zip")
            if not os.path.splitext(file.name)[1] in [".zip"]:
                raise ValidationError("Doesn't have proper extension")

                return file
            else:
                raise ValidationError("Couldn't read uploaded file")

...这是我用于该表单的视图:

...and here's the view I'm using for that form:

def post_product(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ProductForm(data = request.POST, files = request.FILES)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            product = form.save(commit = False)
            product.user = request.user
            product.likes = 0
            product.save()
        # redirect to a new URL:
        return HttpResponseRedirect('/products')

我想念什么?

推荐答案

在您看来,无论表单是否有效,您都在进行重定向-因此Django无处显示表单错误.

In your view, you are doing a redirect regardless of whether or not the form is valid - so there is nowhere for Django to show form errors.

通常的方法是在 is_valid() False 时重新呈现表单:

The normal way to do this would be to re-render the form when is_valid() is False:

if form.is_valid():
    # process the data in form.cleaned_data as required
    product.save()
    # redirect to a new URL - only if form is valid!
    return HttpResponseRedirect('/products')
else:
    ctx = {"form": form} 
    # You may need other context here - use your get view as a template
    # The template should be the same one that you use to render the form
    # in the first place.
    return render(request, "form_template.html", ctx}

您可能要考虑使用基于类的

You may want to consider using a class-based FormView for this, as it handles the logic of re-rendering forms with errors. This is simpler and easier than writing two separate get and post views to manage your form. Even if you don't do that, it will be easier to have a single view that handles both GET and POST for the form.

这篇关于Django Forms Validation消息未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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