如何在重写 save_model() 函数时在 admin.py 中使用验证?

发布于 2024-10-19 07:16:56 字数 811 浏览 1 评论 0原文

Admin.py

class CourseAdmin(admin.ModelAdmin):

list_display = ('course_code', 'title', 'short' )

 def save_model(self, request, obj, form, change):
    import os

    #obj.author = request.user
    dir_name = obj.course_code
    path = settings.MEDIA_ROOT +os.sep+'xml'+os.sep+dir_name

    #if user updates course name then course would be renames
    if change:
        dir_name = Course.objects.get(pk=obj.pk).course_code
        src = settings.MEDIA_ROOT +os.sep+'xml'+os.sep+dir_name      
        os.rename(src,path)
    else:
        if not os.path.exists(path):
            os.makedirs(path)
            obj.save()

        else:
            raise ValidationError('Bla Bla')


admin.site.register(Course, CourseAdmin)

当我提出验证错误时,它不起作用并显示错误页面 异常类型:验证错误 异常值:[u'Bla Bla']

Admin.py

class CourseAdmin(admin.ModelAdmin):

list_display = ('course_code', 'title', 'short' )

 def save_model(self, request, obj, form, change):
    import os

    #obj.author = request.user
    dir_name = obj.course_code
    path = settings.MEDIA_ROOT +os.sep+'xml'+os.sep+dir_name

    #if user updates course name then course would be renames
    if change:
        dir_name = Course.objects.get(pk=obj.pk).course_code
        src = settings.MEDIA_ROOT +os.sep+'xml'+os.sep+dir_name      
        os.rename(src,path)
    else:
        if not os.path.exists(path):
            os.makedirs(path)
            obj.save()

        else:
            raise ValidationError('Bla Bla')


admin.site.register(Course, CourseAdmin)

when i raise validation Error it doesn't work and shows error page with
Exception Type: Validation Error
Exception Value:[u'Bla Bla']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

余生共白头 2024-10-26 07:16:56

在自定义 ModelForm 中进行验证,然后告诉您的 ModelAdmin 使用该表单。

Django 文档的这一部分 应该可以帮助你。

Do your validation in a custom ModelForm, then tell your ModelAdmin to use that form.

This part of the Django Documentation should help you out.

半城柳色半声笛 2024-10-26 07:16:56

根据 模型管理方法 上的 django 文档, save_model() 必须保存对象无论如何。您仅使用此方法在保存之前执行额外的处理。我同意 Wogan 的观点,您应该创建一个自定义 ModelForm 并覆盖其 clean() 方法并在那里引发错误。

As per django documentation on model admin methods, the save_model() Must save the object no matter what. You only use this method for performing extra processing before save. I agree with Wogan, you should just create a custom ModelForm and override its clean() method and raise the error there.

空宴 2024-10-26 07:16:56

这是一个例子:

def clean_name(self):
    如果有什么:
        引发 forms.ValidationError("出了问题")
    返回 self.cleaned_data["name"]

Here's an example:

def clean_name(self):
    if something:
        raise forms.ValidationError("Something went wrong")
    return self.cleaned_data["name"]
缘字诀 2024-10-26 07:16:56

创建一个表单:

您应该在 CourseAdminForm 中

class CourseAdminForm(forms.ModelForm):

    def clean(self):
        raise ValidationError("Bla Bla") 

you should create a form-

inside your CourseAdminForm:

class CourseAdminForm(forms.ModelForm):

    def clean(self):
        raise ValidationError("Bla Bla") 
救星 2024-10-26 07:16:56

您可以使用类似的内容,

from django.contrib import messages

messages.error(request, '<Your message>')

它将被保存,但用户可以看到有什么问题。

You can use something like that

from django.contrib import messages

messages.error(request, '<Your message>')

it will be saved but user can to see that something is wrong.

任性一次 2024-10-26 07:16:56

最简单的方法,无需创建自定义表单然后使用它:

1.在您的 Models.py 中添加“blank=True”,例如:

Zone_Name = models.CharField(max_length=100L,unique=True,blank=True )

2.创建或添加到 Models.py 同一类中的现有 Clean 方法(不在 Admin.py 中)您想要的字段的验证,例如:

def clean(self):
         if self.Zone_Name == None or not self.Zone_Name :
            raise ValidationError("Zone name is not given!")

Easiest way to do it, without creating a custom form and then using it:

1.In Your Models.py add "blank=True" for example:

Zone_Name = models.CharField(max_length=100L,unique=True,blank=True )

2.Create or add to an existing Clean method in the same class of Models.py (not in Admin.py) the validation on the field that you want, for example:

def clean(self):
         if self.Zone_Name == None or not self.Zone_Name :
            raise ValidationError("Zone name is not given!")
末骤雨初歇 2024-10-26 07:16:56

您应该以自定义形式编写验证逻辑,这是一个完整的示例:

# Created by [email protected] at 2022/4/26
from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class UserAdminForm(forms.ModelForm):
    # Show error on username field
    def clean_username(self):
        username = self.cleaned_data.get("username")
        if len(username) <= 6:
            raise ValidationError("Username is illegal")
        return username

    # Show error on form top
    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get("username") == cleaned_data.get("password"):
            raise ValidationError("Password must not be equal to username")
        return cleaned_data


class UserAdmin(admin.ModelAdmin):
    model = User
    form = UserAdminForm

You should write validation logic in custom form, here is a complete example:

# Created by [email protected] at 2022/4/26
from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class UserAdminForm(forms.ModelForm):
    # Show error on username field
    def clean_username(self):
        username = self.cleaned_data.get("username")
        if len(username) <= 6:
            raise ValidationError("Username is illegal")
        return username

    # Show error on form top
    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get("username") == cleaned_data.get("password"):
            raise ValidationError("Password must not be equal to username")
        return cleaned_data


class UserAdmin(admin.ModelAdmin):
    model = User
    form = UserAdminForm

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文