I successfully extended some admin model and form, but I’m not sure how to keep my file tree clean.
If I put forms.py at the same level as admin.py, everything work perfectly:
forms.py
class MyUserCreationForm(UserCreationForm):
#...
class MyUserChangeForm(UserChangeForm):
#...
admin.py
from myapp.forms import MyUserCreationForm, MyUserChangeForm
File tree
mypackage/
admin.py
forms.py
Now, in order to have my admin-related forms separated from the other forms and make the code cleaner, I added a folder admin to put my admin-related forms. In that case URLs seem to be messed up. When going to /myapp/admin/ I get the default admin page, not the one I customized in my admin.py.
admin/forms.py
class MyUserCreationForm(UserCreationForm):
#...
class MyUserChangeForm(UserChangeForm):
#...
admin.py
from myapp.admin.forms import MyUserCreationForm, MyUserChangeForm
File tree
mypackage/
admin.py
admin/
forms.py
I guess the system is confused because admin is both a file and a folder. What’s the standard way to keep custom admin-related files in Django?
EDIT: in the case shown above, there is a conflict between admin.py and the folder admin. I tried to put admin.py and forms.py in a folder, but it still does not work:
admin/forms.py
class MyUserCreationForm(UserCreationForm):
#...
class MyUserChangeForm(UserChangeForm):
#...
admin/admin.py
from myapp.admin.forms import MyUserCreationForm, MyUserChangeForm
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
list_filter = ()
fieldsets = (
(None, {'fields': ('username', 'number', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'number', 'password1', 'password2')}
),
)
admin.site.register(MyUser, MyUserAdmin)
File tree
mypackage/
admin/
forms.py
admin.py
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Firstly, you need to create an
__init__.pyfile in your admin directory in order for it to be treated as a package.The
__init__.pyfile is often empty. See the Python docs on packages for more information.Secondly, you cannot have a directory called
adminand a fileadmin.py. When you runimport myapp.admin, python will ignore theadmin.pyfile, and loadadmin/__init__.pyinstead.One possible solution is for you to move
admin.pytoadmin/__init__.py. Then the following imports should work properly.