Models not showing in Admin Interface - django

I can not get my models to display within the Admin Interface even after registering them in django-admin.py using admin.site.register(topic).
I have registered a model class topic, but it just isn't showing up in the interface. Instead, I'm getting groups and users in the auth section and sites in the sites section.
Below is the code I currently have. Any help would be appreciated.
models.py
class topic(models.Model):
topic_name = models.CharField(max_length=30)
description=models.CharField(max_length=255,null=True, blank = True)
class Admin:
pass
def str__(self):
return '%s''--' %(self.topic_name)
admin.py
from django.contrib import admin
from edc.kds.models import *
if __name == "main":
management.execute_from_command_line()
admin.site.register(topic)

You're doing some strange stuff.
1: You have some ancient, years old class Admin syntax which isn't necessary.
2: You have a strange if __name block in there. Clearly that should raise a NameError, but assuming you actually wrote __name__ == 'main', there's your problem.
__name__ is set to 'main' only if the file is directly executed. If it's executed by django machinery, the if block will never fire, and thus admin.site.register will never be called.
Where'd you get this idea?

# urls.py
from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
)

Related

enable a model on Django Admin on Dreamhost

Hi I've created a new app (Paginas) but I cannot see inside the admin page. I've added 'paginas' to INSTALLED_APP. My admin.py is
# coding=utf-8
from django.contrib import admin
from .models import Pagina
class PaginaAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("titulo",)}
list_display = ('titulo' , 'contenido')
class Media:
js = ('/layout/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js','/layout/grappelli/tinymce_setup/tinymce_setup.js')
admin.site.register(Pagina,PaginaAdmin)
I am using passenger_wsgi.py file, I've touched tmp/restart.txt file, I've killed python process
I don't know what else can I do
The project you can see it on github https://github.com/totechess/paralisis_cerebral
What kind of error do you get when you go to your site yoursite.com/admin/
Did you add admin to INSTALLED_APPS? Note the S
....
'django.contrib.admin',
....
Perhaps your urls.py are not updated properly? What is the error?

Issues with 2 different admin sites in a Django

I want to have 2 separate admin sites inside a Django project.
First is default admin
And Second is "coursemanager"
Following code i have added with the help of AdminSite
File Path "cms/courses/admin.py"
from courses.models import *
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
class CourseManager(AdminSite):
name = 'CourseManager'
course_manager = CourseManager()
class CityAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'status',]
list_filter = ['status',]
search_fields = ['title',]
course_manager.register(City, CityAdmin)
"cms/cms/urls.py"
from courses.admin import course_manager
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'coursemanager/', include(course_manager.urls)),
)
But when i add this http://domain.local/coursemanager/ & http://domain.local/admin/ both panel is working but in http://domain.local/coursemanger/ list register city module but not showing the add or changes links. Event i tried to access links from url but not working. I am checking this as superuser and i have all modules access. But when i change code like bellow
"cms/cms/urls.py"
from courses.admin import course_manager
urlpatterns = patterns('',
url(r'coursemanager/', include(course_manager.urls)),
url(r'^admin/', include(admin.site.urls)),
)
Then http://domain.local/coursemanager/ working properly and http://domain.local/admin panel is only listing all register admin but not showing the add/change links.
The app_name of AdminSite() is initialized through AdminSite.__init__(). You cannot override it by providing class-level variable, thus you were experiencing instance namespace collision and then some reverse failure, here, which caused add/change links not showing. Try
class CourseManager(AdminSite):
'...'
course_manager = CourseManager(name='CourseManager')
# or
course_manager = AdminSite(name='CourseManager')

How can I not use Django's admin login view?

I created my own view for login. However if a user goes directly to /admin it brings them to the admin login page and doesn't use my custom view. How can I make it redirect to the login view used for everything not /admin?
From http://djangosnippets.org/snippets/2127/—wrap the admin login page with login_required. For example, in urls.py:
from django.contrib.auth.decorators import login_required
from django.contrib import admin
admin.autodiscover()
admin.site.login = login_required(admin.site.login)
You probably already have the middle two lines and maybe even the first line; adding that fourth line will cause anything that would have hit the admin.site.login function to redirect to your LOGIN_URL with the appropriate next parameter.
While #Isaac's solution should reject majority of malicious bots, it doesn't provide protection for professional penetrating. As a logged in user gets the following message when trying to login to admin:
We should instead use the admin decorator to reject all non-privileged users:
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import admin
[ ... ]
admin.site.login = staff_member_required(admin.site.login, login_url=settings.LOGIN_URL)
To the best of my knowledge, the decorator was added in 1.9.
I found that the answer above does not respect the "next" query parameter correctly.
An easy way to solve this problem is to use a simple redirect. In your site's urls file, immediately before including the admin urls, put a line like this:
url(r'^admin/login$', RedirectView.as_view(pattern_name='my_login_page', permanent=True, query_string=True))
Holá
I found a very simple solution.
Just tell django that the url for admin login is handle by your own login view
You just need to modify the urls.py fle of the project (note, not the application one)
In your PROJECT folder locate the file urls.py.
Add this line to the imports section
from your_app_name import views
Locate this line
url(r'^admin/', include(admin.site.urls))
Add above that line the following
url(r'^admin/login/', views.your_login_view),
This is an example
from django.conf.urls import include, url
from django.contrib import admin
from your_app import views
urlpatterns = [
url(r'^your_app_start/', include('your_app.urls',namespace="your_app_name")),
url(r'^admin/login/', views.your_app_login),
url(r'^admin/', include(admin.site.urls)),
]
http://blog.montylounge.com/2009/07/5/customizing-django-admin-branding/
(web archive)
I'm trying to solve exactly this problem and I found the solution at this guys blog. Basically, override the admin template and use your own template. In short, just make a file called login.html in /path-to-project/templates/admin/ and it will replace the admin login page. You can copy the original (django/contrib/admin/templates/login.html) and modify a line or two. If you want to scrap the default login page entirely you can do something like this:
{% extends "my-login-page.html" %}
There it is. One line in one file. Django is amazing.
I had the same issue, tried to use the accepted answer, but has the same issue as pointed in the comment above.
Then I've did something bit different, pasting here if this would be helpful to someone.
def staff_or_404(u):
if u.is_active:
if u.is_staff:
return True
raise Http404()
return False
admin.site.login = user_passes_test(
staff_or_404,
)(admin.site.login)
The idea is that if the user is login, and tried to access the admin, then he gets 404. Otherwise, it will force you to the normal login page (unless you are already logged in)
In your ROOT_URLCONF file (by default, it's urls.py in the project's root folder), is there a line like this:
urlpatterns = patterns('',
...
(r'^admin/', include(admin.site.urls)),
...
)
If so, you'd want to replace include(admin.site.urls) with the custom view you created:
(r'^admin/', 'myapp.views.myloginview'),
or if your app has its own urls.py, you could include it like this:
(r'^admin/', include(myapp.urls)),
This is my solution with custom AdminSite class:
class AdminSite(admin.AdminSite):
def _is_login_redirect(self, response):
if isinstance(response, HttpResponseRedirect):
login_url = reverse('admin:login', current_app=self.name)
response_url = urllib.parse.urlparse(response.url).path
return login_url == response_url
else:
return False
def admin_view(self, view, cacheable=False):
inner = super().admin_view(view, cacheable)
def wrapper(request, *args, **kwargs):
response = inner(request, *args, **kwargs)
if self._is_login_redirect(response):
if request.user.is_authenticated():
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
else:
return redirect_to_login(request.get_full_path(), reverse('accounts_login'))
else:
return response
return wrapper
You can redirect admin login url to the auth login view :
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('your_app.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('admin/login/', RedirectView.as_view(url='/accounts/login/?next=/admin/', permanent=True)),
path('admin/', admin.site.urls),
]
As of August 2020, django.contrib.admin.sites.AdminSite has a login_template attribute. So you can just subclass AdminSite and specify a custom template i.e.,
class MyAdminSite(AdminSite):
login_template = 'my_login_template.html'
my_admin_site = MyAdminSite()
Then just use my_admin_site everywhere instead of admin.site.

Django: Using 2 different AdminSite instances with different models registered

Apart from the usual admin, I want to create a limited admin for non-staff users. This admin site will have different registered ModelAdmins.
I created a folder /useradmin/ in my project directory and similar to contrib/admin/_init_.py I added an autodiscover() which will register models defined in useradmin.py modules instead of admin.py:
# useradmin/__init__.py
def autodiscover():
# Same as admin.autodiscover() but registers useradmin.py modules
...
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.useradmin' % app)
except:
site._registry = before_import_registry
if module_has_submodule(mod, 'useradmin'):
raise
I also cretated sites.py under useradmin/ to override AdminSite similar to contrib/admin/sites:
# useradmin/sites.py
class UserAdminSite(AdminSite):
def has_permission(self, request):
# Don't care if the user is staff
return request.user.is_active
def login(self, request):
# Do the login stuff but don't care if the user is staff
if request.user.is_authenticated():
...
else:
...
site = UserAdminSite(name='useradmin')
In the project's URLs:
# urls.py
from django.contrib import admin
import useradmin
admin.autodiscover()
useradmin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^useradmin/', include(useradmin.site.urls)),
)
And I try to register different models in admin.py and useradmin.py modules under app directories:
# products/useradmin.py
import useradmin
class ProductAdmin(useradmin.ModelAdmin):
pass
useradmin.site.register(Product, ProductAdmin)
But when registering models in useradmin.py like useradmin.site.register(Product, ProductAdmin), I get 'module' object has no attribute 'ModelAdmin' exception. Though when I try this via shell;
import useradmin
from useradmin import ModelAdmin
does not raise any exception.
Any ideas what might be wrong?
Edit:
I tried going the #Luke way and arranged the code as follows as minimal as possible:
(file paths are relative to the project root)
# admin.py
from django.contrib.admin import autodiscover
from django.contrib.admin.sites import AdminSite
user_site = AdminSite(name='useradmin')
# urls.py (does not even have url patterns; just calls autodiscover())
import admin
admin.autodiscover()
# products/admin.py
import admin
from products.models import Product
admin.user_site.register(Product)
As a result I get an AttributeError: 'module' object has no attribute 'user_site' when admin.user_site.register(Product) in products/admin.py is called.
Any ideas?
Solution:
I don't know if there are better ways but, renaming the admin.py in the project root to useradmin.py and updating the imports accordingly resolved the last case, which was a naming and import conflict.
Does useradmin have a ModelAdmin class defined, or do you import it from contrib.admin? I don't see anywhere in the code you supplied where that class gets set up.
That being said, there's a much easier way to do this: just initialize two AdminSites, and then wire them up to the URLs that you want (You can even put them in the same urlconf).

django ignoring admin.py

I am trying to enable the admin for my app. I managed to get the admin running, but I can't seem to make my models appear on the admin page.
I tried following the tutorial (here) which says:
(Quote)
Just one thing to do: We need to tell
the admin that Poll objects have an
admin interface. To do this, create a
file called admin.py in your polls
directory, and edit it to look like
this:
from polls.models import Poll from
django.contrib import admin
admin.site.register(Poll)
(end quote)
I added an admin.py file as instructed, and also added the following lines into urls.py:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
...
(r'^admin/', include(admin.site.urls)),
)
but it appears to have no effect. I even added a print 1 at the first line of admin.py and I see that the printout never happens, So I guess django doesn't know about my admin.py. As said, I can enter the admin site, I just don't see anything other than "groups", "users" and "sites".
What step am I missing?
You need to ensure you have app containing Poll listed in INSTALLED_APPS :)
Also: If you're adding the admin.py file with the dev server running, make sure to restart it. This tripped me up for a minute. :)