jamylak
jamylak

Reputation: 133724

Changing default django admin widget site wide

I want to modify the widget used by models.URLField to include a dropdown with internal links in my site (similar to any-urlfield but detected from the sitemap).

I want to have every external app that uses a models.URLField use this custom widget and not have to redefine each individual app formfield_overrides.

I looked into django/contrib/admin/options.py and found

FORMFIELD_FOR_DBFIELD_DEFAULTS = {
 ...
 models.TextField: {'widget': widgets.AdminTextareaWidget},
 models.URLField: {'widget': widgets.AdminURLFieldWidget},
 models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
 models.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget},
 ...
}

Essentially I would like to change this default if it were possible. How would I go about changing the default widget for a field in the django admin site wide.

Upvotes: 1

Views: 582

Answers (1)

catavaran
catavaran

Reputation: 45585

Why not to update this dictionary? Place this code to any admin.py file.

from django.contrib.admin import options
from django.db import models
from django.forms import widgets

options.FORMFIELD_FOR_DBFIELD_DEFAULTS[models.URLField] = {
                                           'widget': widgets.TextInput}

UPDATE: To make this work you should place this line at the top of the admin.py before any admin.site.register() calls. Also you need to move the app with such admin.py somewhere at top of the INSTALLED_APPS list. This change will affect all apps loaded after the mentioned app.

Upvotes: 3

Related Questions