开发者

Validation to site.domain fieald

开发者 https://www.devze.com 2023-03-12 04:54 出处:网络
I import from django.contrib.sites.开发者_Go百科models import Sitein models.py file. In have this following in admin.py file:

I import from django.contrib.sites.开发者_Go百科models import Site in models.py file.

In have this following in admin.py file:

class SitesAdmin(admin.ModelAdmin):    
    pass

admin.site.unregister(Site)
admin.site.register(Site, SitesAdmin)**

I want to attach validation to the site.domain field in admin.py, How i can accomplish this? please help.


First, specifying an empty ModelAdmin class is unnecessary, the following will work if you don't need to customize the admin:

admin.site.register(Site) # Notice that no ModelAdmin is passed

Now, to your question. You have to create a custom form. Then, you override the clean_domain method of the ModelForm. You can validate any field with the method(s) clean_FOO, where FOO is the field name.

from django import forms

class SiteAdminForm(forms.ModelForm):

    def clean_domain(self):
        domain = self.cleaned_data.get('domain')
        # Custom validation here

        return domain

class SiteAdmin(admin.ModelAdmin):
    form = SiteAdminForm

admin.site.unregister(Site)
admin.site.register(Site, SiteAdmin)    
0

精彩评论

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