Auto register Django auth models using custom admin site - django

I implemented authentication management using Django auth with the default admin site but then I wanted to use my own AdminSite to rewrite some behaviors:
class OptiAdmin(admin.AdminSite):
site_title = "Optimizer site's admin"
#...Other stuff here
Then registered my own models:
admin_site = OptiAdmin(name='opti_admin')
admin.site.register(MyModel, MyModelAdmin)
#Other stuff here
But when I go to the admin site I am only able to see the models I just registered, which sounds fair to me but I would like to see all the other apps models in this new custom site including the auth's users and groups and I don't know how to do this automatically like the default admin does, pls help :).

Create your own AdminSite with a simple __init__() override.
Import your admin in urls.py.
Replacing the Django Admin and getting the autodiscover() behavior is possible with minimal effort. Here's a project structure generated in the typical django-admin startproject project fashion:
project/
manage.py
project/
__init__.py
settings.py
urls.py
wsgi.py
admin.py # CREATE THIS FILE
project/admin.py: (I think it makes the most sense to do this at the project level.)
from django.contrib.admin import * # PART 1
class MyAdminSite(AdminSite):
site_header = "My Site"
def __init__(self, *args, **kwargs):
super(MyAdminSite, self).__init__(*args, **kwargs)
self._registry.update(site._registry) # PART 2
site = MyAdminSite()
project/urls.py (snippet):
from . import admin # PART 3
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
Part 1 is simple Python. By importing everything from django.contrib.admin into your namespace, it acts as a drop-in replacement. I suppose you don't have to do this, but it helps preserve expectations. Part 3, simply connect up your admin. Part 2 is the real trick. As the documentation says, autodiscover() is called to do the work. All autodiscover does is go through INSTALLED_APPS attempting to import a file called admin.py. Importing runs the code of course and that code is doing the same thing you do to register models (example by decorator and example by method). No magic. You don't have to register your models with your customized admin (as the documentation says).
Autodiscover looks smarter than it is with its register_to kwarg. That indicates you could call autodiscover() yourself passing your own admin. Nope; there's no wiring connected there (future feature?). The assignment happens here and is fixed to the native AdminSite instance here (or here using the decorator). Django contrib models register to that instance and so will any third-party libraries. It's not something you can hook into.
Here's the trick though, _registry is just a dictionary mapping. Let Django autodiscover all the things and then just copy the mapping. That's why self._registry.update(site._registry) works. "self" is your customized AdminSite instance, "site" is Django's instance and you can register your models with either.
(Final note: If models are missing, it's because of import order. All the registration to Django's AdminSite needs to happen before you copy _registry. Registering directly to your customized admin is probably the easiest thing.)

The Django docs suggest using SimpleAdminConfig with a custom admin site.
INSTALLED_APPS = (
...
'django.contrib.admin.apps.SimpleAdminConfig',
...
)
That prevents the models being registered with the default AdminSite.
The docs seem to assume that you will import the models individually and add them to your custom admin site:
from django.contrib.auth.models import Group, User
from django.contrib.auth.admin import GroupAdmin, UserAdmin
admin_site.register(Group, GroupAdmin)
admin_site.register(User, UserAdmin)
This would be very repetitive if you have models in many apps. It doesn't offer any advice how to automatically register models from all your apps with your custom site.
You could try monkey patching admin, and replacing admin.site with your own.
from django.contrib import admin
admin.site = OptiAdmin(name='opti_admin')
Then, when code called admin.site.register(), it would register the model with your admin site. This code would have to run before any models were registered. You could try putting it in the AppConfig for your app, and make sure that your app is above django.contrib.admin.

Adding to JCotton's great answer:
Using django 2.0, overriding site_header and site_title in the custom admin site only works for the index page.
To get it to work with all admin views, extend JCotton's code with the following:
def __init__(self, *args, **kwargs):
super(MyAdminSite, self).__init__(*args, **kwargs)
self._registry.update(site._registry) # PART 2
for model, model_admin in self._registry.items():
model_admin.admin_site = self

Just include init method in your CustomAdminSite class like this.
class CustomAdminSite(admin.AdminSite):
def __init__(self, *args, **kwargs):
super(CustomAdminSite, self).__init__(*args, **kwargs)
self._registry.update(admin.site._registry)

Related

Extend django-invitations + django-allauth account adapter

I'm using django-allauth and django-invitations. Following django-allauth's docs, I have created a custom adapter so I can override the get_signup_redirect_url method
from allauth.account.adapter import DefaultAccountAdapter
class MyAccountAdapter(DefaultAccountAdapter):
def get_login_redirect_url(self, request):
# custom redirects here
And then in my settings file I have
ACCOUNT_ADAPTER = 'accounts.adapter.MyAccountAdapter'
I'm also using django-invitations, whose docs say that for integrating with allauth, I need to set
ACCOUNT_ADAPTER = 'invitations.models.InvitationsAdapter'
This obviously causes a problem because then I'm no longer using my custom adapter.
How can I integrate django-allauth and django-invitations while also overriding the adapter get_login_redirect_url method?
This is how I solved the problem in django-invitations v1.9. Hopefully it's not relevant in the near future.
In my project, I have an "accounts" app where I put all my accounts related files. In the __init__.py for the app, I put the following delightful monkey patch đŸ™‰
from invitations import adapters
def new_get_invitations_adapter():
from allauth.account.adapter import get_adapter
return get_adapter()
adapters.get_invitations_adapter = new_get_invitations_adapter
It just bypasses the django-invitations logic that works out which adapter to use by always returning the one django-allauth would use. And django-allauth returns the custom one, which I specified in the project settings.py.
ACCOUNT_ADAPTER = 'accounts.adapters.MyAccountAdapter'

Registering Django system checks in AppConfig's ready() method

In the docs for Django's System check framework it says:
Checks should be registered in a file that’s loaded when your application is loaded; for example, in the AppConfig.ready() method.
None of the examples on that page, or around the AppConfig.ready() method, show how to do this. Given a checking method like:
from django.core.checks import register, Tags
#register(Tags.compatibility)
def my_check(app_configs, **kwargs):
# ... perform compatibility checks and collect errors
return errors
How would you do this in/from the AppConfig.ready() method? Is one called from the other? Which file should the above method go in? Do you add #register(...) to the ready() method?
From reading the examples on this page about the Apps Registry and System Checks Framework, it seems there are (at least) two ways to add your own System Checks. To adapt that page's examples (assuming you're creating an app called myapp):
1) Create a myapp/checks.py file like this:
from django.apps import apps as camelot_apps
from django.core.checks import register, Warning
from django.core.checks import Tags as DjangoTags
class Tags(DjangoTags):
"""Do this if none of the existing tags work for you:
https://docs.djangoproject.com/en/1.8/ref/checks/#builtin-tags
"""
my_new_tag = 'my_new_tag'
#register(Tags.my_new_tag)
def check_taggit_is_installed(app_configs=None, **kwargs):
"Check that django-taggit is installed when usying myapp."
errors = []
try:
from taggit import models
except ImportError:
errors.append(
Warning(
"The django-taggit app is required to use myapp.",
hint=("Install django-taggit"),
# A unique ID so it's easier to find this warning:
id='myapp.W001',
)
)
return errors
And then in myapp/__init__.py (create it if it doesn't exist):
from . import checks
Running this should run that check above:
$ ./manage.py check myapp
2) Or, as I thought in my initial question, you can register that check in your AppConfig. So, keep the above code in myapp/check.py, but remove the #register(Tags.my_new_tag) line.
Then create myapp/apps.py containing this:
from django.core.checks import register
from .checks import Tags, check_taggit_is_installed
class MyappConfig(AppConfig):
name = 'myapp'
def ready(self):
super(MyappConfig, self).ready()
register(Tags.my_new_tag)(check_taggit_is_installed)
And alter myapps/__init__.py so it contains this:
from . import checks
default_app_config = 'myapp.apps.MyappConfig'
The first example seems simpler, with no need for a custom AppConfig.
Django recommends:
Checks should be registered in a file that’s loaded when your application is loaded; for example, in the AppConfig.ready() method.
Therefore, place the checks code in a checks.py file. Then simply in apps.py, as with signals:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'MyApp'
verbose_name = "My App"
def ready(self):
# import myapp.signals
import myapp.checks
My guess is that you can just place this code in ready() method. For example of usage you can take a look at django.contrib.auth (or other contrib app). This app has check in checks.py file, that imported in apps.py and registered in ready() method: checks.py, apps.py.

django admin super(type, obj)

Well, let me explain this.
I am working on a simple django admin project.
In the admin.py file, I have the following admin classes:
class A_Admin(admin.ModelAdmin):
#some stuff
class B_Admin(admin.ModelAdmin):
#some stuff
I want to override the get_urls() method of A_Admin that if I click a button on A_Admin instance change page, it will redirect the page to B_Admin changelist page.
(I know there are many ways to do what I want and what I mentioned above is not the best, but this is what I want. So let skip the discussion why I insist on this solution.)
I want to the following:
def get_urls(self):
#django's code
#inside the urlpattern
urlpattern = (
#default urls from django admin
.....
url(r'^some_url$',
wrap(super(B_Admin, self).changelist_view),
name='%s_%s_delete' % info),
....)
return urlpatterns
This is not working, since 'self' is a A_Admin class object rather than B_Admin obejct.
So is there any way to get the proxy of calss A_Admin inside B_Admin?
I just wanna override changelist_view of A and call it inside B.
Is this possible?
Thanks in advance
You should just instantiate B_Admin and use its method.
I believe the following code should work:
from django.contrib import admin
from my_app.models import B_Model # The model for which B_Admin is used
def get_urls(self):
#django's code
#inside the urlpattern
urlpattern = (
#default urls from django admin
.....
url(r'^some_url$',
wrap(B_Admin(B_Model, admin.site).changelist_view),
name='%s_%s_delete' % info),
....)
return urlpatterns
UPDATE: Most probably, B_Admin was already instantiated when you called
admin.site.register(B_Model, B_Admin)
So instead of doing
B_Admin(B_Model, admin.site)
again you can just get it from the AdminSite's registry:
admin.site._registry[B_Model]

Best practice for Django sites to set up site configuration variables?

all! I am writing a Django blog site.
I am new to Django. Since Django has the philosophy of loose coupling, I believe it's best to follow their beliefs when using their framework.
So I am encountering a dilemma here:
I want to set up some variables for my blog, say, the blog title, slogan, and the maximum length of digest on the homepage of each blog I wrote, and how many blog digest should I display on the homepage per page.
I can do this by creating a new app in my Django project, and create models for my site's config variables, then read those variables from other app, but this practice obviously breaks the philosophy of loose coupling.
The only work around I can think of is setting up environment variables in my sites .wsgi file (I use Apache and mod_wsgi to serve Python scripts) But I don't think messing up with environment variable is 'clean' enough.
Can anyone suggest me a better solution?
First thing you can do is set up those variables in your project's settings module, many apps do that:
# settings
BLOG_TITLE = 'My title'
Then, a good practice is to provide settings defaults, so your app should have a settings file
# blog/settings.py
from django.conf import settings
BLOG_TITLE = getattr(settings, 'BLOG_TITLE', 'MY default title')
# Then wherever, views or context processor
from blog import settings # See how we're not importing project's settings
title = settings.BLOG_TITLE
Another alternative is to create a "Blog" model that contains all those variables, this may invite you to make your app to have a blog tied per Django sites
from django.contrib.sites.models import Site
class Blog(models.Model):
site = models.OneToOneField(Site) # Tied up to a Django site
title = models.CharField(max_length=256)
Now you can change those values from your Admin interface and use them in your views or context processor
site = Site.objects.get_current() # Installed Django Sites app and middleware
blog = site.blog
print blog.title
You can create settings or constants file in your app folder and use it. This way all your constants will be bound to your application:
apps/
blog/
__init__.py
models.py
urls.py
constants.py # <-- here it is!
File can look like this:
BLOG_TITLE = 'My super blog'
# ...
And you can use tour constants like this:
import blog.constants
# ...
return render_to_response('index.html', {title: blog.constants.BLOG_TITLE})
And in template:
<title>{{ title }}</title>
In my opinion, the best way to do this is by adding a model related to Site model using inheritance
First add site id to your Django settings file
SITE_ID = 1
now create a model in an app
from django.db import models
from django.contrib.sites.models import Site
class Settings(Site):
field_a = models.CharField(max_length=150, null=True)
field_b = models.CharField(max_length=150, null=True)
class Meta:
verbose_name_plural = 'settings'
db_table = 'core_settings' # core is name of my app
def __str__(self) -> str:
return 'Settings'
then edit apps.py file of that app
from django.apps import AppConfig
from django.db.models.signals import post_migrate
def build_settings(sender, **kwargs):
from django.contrib.sites.models import Site
from .models import Settings
if Settings.objects.count() < 1:
Settings.objects.create(site_ptr=Site.objects.first())
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'project.apps.core'
def ready(self) -> None:
post_migrate.connect(build_settings, sender=self)
now every time you run migrations a row will auto-generated in core_settings that have a one to one relationship with your Site model
and now you can access to your settings like this
Site.objects.get_current().settings.access_id
optional: if have only a single site
unregister site model from admin site and disable creating and deleting settings model in admin panel
from django.contrib import admin
from . import models
from django.contrib.sites.models import Site
admin.site.unregister(Site)
#admin.register(models.Settings)
class SettingAdminModel(admin.ModelAdmin):
def has_delete_permission(self, request,obj=None) -> bool:
return False
def has_add_permission(self, request) -> bool:
return False

Django - Extending another apps ModelAdmin?

Is there a way to extend another apps ModelAdmin?
I have a project that uses functionality offered by django.contrib.comments.
The CommentsAdmin ModelAdmin class has:
actions = ["flag_comments", "approve_comments", "remove_comments"]
I would like to extend the CommentsAdmin ModelAdmin in my project to include an action ban_user.
I've tried creating my own NewCommentsAdmin(CommentsAdmin) object in my admin.py file and registering it, but I get a notice 'AlreadyRegistered at /admin/' 'The model Comment is already registered'.
class NewCommentAdmin(CommentAdmin):
actions = ['ban_user']
def ban_user(self, request, queryset):
pass
admin.site.register(Comment, NewCommentAdmin)
Is there a way to do this without modifying the original django.contrib.comments code?
Here's how I do it in one project for the User model. In the admin.py for my app:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
# ...
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
Unregister the Comment model first.
I guess you have something like this at the top of your file:
from django.contrib.comments.admin import CommentAdmin
This import executes the registration of the model (at the very bottom of this admin file) again.
One idea that doesn't look very nice (I actually haven't tried it) could be:
from django.contrib.comments.models import Comment
from django.contrib import admin
from django.contrib.admin.sites import NotRegistered
# Try to unregister the Comment model
# that was registered via the auto_discover method
try:
admin.site.unregister(Comment)
except NotRegistered:
pass
# Now we can load the CommentAdmin (which reregisters the admin model)
from django.contrib.comments.admin import CommentAdmin
# We have to unregister again:
try:
admin.site.unregister(Comment)
except NotRegistered:
pass
# Now your stuff...
I guess this could be done better but it should work. To make this approach work, the application that contains this file has to be after the comments application in INSTALLED_APPS.
Now to your class. I think if you write actions = ['ban_user'] you actually overwrite all the actions in the parent class. I think it is the easiest way to override the get_actions method:
class NewCommentAdmin(CommentAdmin):
def get_actions(self, request):
actions = super(NewCommentAdmin, self).get_actions(request)
# Do some logic here based on request.user if you want
# to restrict the new action to certain users
actions.append('ban_user')
return actions
def ban_user(self, request, queryset):
pass
admin.site.register(Comment, NewCommentAdmin)
Hope that helps (or at least gives an idea) :)
Have a look at https://github.com/kux/django-admin-extend
It offers some easy to use functions and decorators that implement the functionality you're requesting in a very flexible manner. The documentation does a pretty good job at explaining why using this approach is better than direct inheritance.
It also has support for injecting bidirectional many to many fields.