开发者

Model validation in Django 1.1

开发者 https://www.devze.com 2023-03-03 13:47 出处:网络
I\'m using Django 1.1I would like to perform validation on a model; specifically, check the extension of a file in a FileField. I can do the extension check fine, but I don\'t know how to show an erro

I'm using Django 1.1 I would like to perform validation on a model; specifically, check the extension of a file in a FileField. I can do the extension check fine, but I don't know how to show an error in the admin panel if it's the wrong extension; similar to when you forget to fill in a required field.

I've tried 2 ways to do it.

  • Make a custom field, based on a filefield and do the validation its clean() method. I can then raise a ValidationError. This works in Django 1.2, but not in 1.1.

  • Overwrite the save() method of the model. I'm unable to throw a ValidationError here though since it just shows a general error page (which regular users won't see) and not a usefu开发者_StackOverflow社区l message in the admin.

Is there any way I can do what I want in Django 1.1?


Django 1.1 doesn't have model validation. The only other place to do validation is on the form - all you have to do is define a custom modelform with your clean method and then tell the admin to use it.

class MyModelForm(forms.ModelForm):
    def clean_myfilefield(self):
        ... do validation or raise forms.ValidationError('message')

class MyModelAdmin(admin.ModelAdmin):
    model = MyModel
    form = MyForm

Note that just checking the extension is not enough to be sure you're getting the file type you expect.

0

精彩评论

暂无评论...
验证码 换一张
取 消