修改后的Django admin clean()方法未被调用 [英] Modified Django admin clean() method not being invoked

查看:116
本文介绍了修改后的Django admin clean()方法未被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经基于Django管理站点开发了一个工具(供内部使用)。

I have developed a tool (to be used internally) based on the Django admin site.

我有合适的模型验证器,但可以做更多工作复杂的验证,我试图覆盖admin.py中的clean()方法

I have model validators in place which work brilliantly, but to do more complex validations, I am attempting to overwrite the clean() method in admin.py

我的admin.py看起来像这样:

My admin.py looks like this:


from django.contrib import admin
from .models import Provider, Employer, Person, Learnership, Qualification, Unit_Standard
from django import forms

class ProviderForm(forms.ModelForm):
class Meta:
model =提供者
字段='全部'

class ProviderForm(forms.ModelForm): class Meta: model = Provider fields = 'all'

    def clean(self):
        provider_start_date = self.cleaned_data.get('provider_start_date')
        provider_end_date = self.cleaned_data.get('provider_end_date')
        if provider_start_date > provider_end_date:
            raise forms.ValidationError("Start date can't be after end date")
        return self.cleaned_data

admin.site.register(提供者)

admin.site.register(Provider)

提供者模型的models.py:

The models.py for the Provider Model:


class Provider(models.Model):
    ... lots of stuff here ...
    provider_start_date = models.DateField()
    provider_end_date = models.DateField(blank=True, null=True)
    ... lots of stuff here ...

    def __str__(self):
        return '%s %s' % (self.provider_name, self.provider_code)

问题是admin.py中显示的代码似乎没有触发,您可以保存结束日期早于开始日期的记录

The problem is that the code displayed in the admin.py doesn't seem to fire, and you can save the record with the end date before the start date.

Django管理界面确实是该框架的一个令人惊奇的功能,我认为其他人也可能会遇到更高级v的问题。

The Django admin interface is really an amazing feature of the framework, and I think that other people have probably also run into this problem of more advanced validations not being possible, so it would help them as well.

推荐答案

您已经创建了模型表单,但是您没有告诉他们

You have created a model form, but you have not told Django to use it.

您应该创建一个模型管理员,并设置 表单 到您的模型表单:

You should create a model admin, and set form to your model form:

class ProviderAdmin(admin.ModelAdmin):
    form = ProviderForm

然后在模型管理类中注册模型:

Then register your model with your model admin class:

admin.site.register(Provider, ProviderAdmin)

这篇关于修改后的Django admin clean()方法未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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