Make new custom view at django admin - python

Sorry, I am still new at django. I want to make custom view at admin site that is not related to my model. I have read the documentation (https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls), but does not work. Reading some tutorials does not work too...
Here is what I tried:
admin.py
from django.contrib import admin
from django.urls import path
from .models import Question
from django.http import HttpResponse
class CustomAdminView(admin.ModelAdmin):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'^my_view/$', self.admin_site.admin_view(self.my_view))
]
urls = my_urls + urls
return urls
def my_view(self, request):
return HttpResponse("Hello, world.")
admin.site.register(Question)
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
admin.autodiscover()
urlpatterns = [
path(r'polls/',include('polls.urls')),
path('admin/', admin.site.urls),
]
when I go to admin/my_view the result is 404 not found.
I tried by extending the AdminView too.
admin.py
from django.contrib.admin import AdminSite
from django.urls import path
from .models import Question
from django.http import HttpResponse
class CustomAdminView(AdminSite):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'my_view/', self.admin_view(self.my_view))
]
urls = my_urls + urls
return urls
def my_view(self, request):
return HttpResponse("Hello, world.")
custom_admin = CustomAdminView()
custom_admin.register(Question)
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from polls.admin import custom_admin
admin.autodiscover()
urlpatterns = [
path(r'polls/',include('polls.urls')),
path('admin/', custom_admin.urls),
]
I don't get 404 error on admin/my_view. But, the default models(user, and others) are not displayed. There is only my 'Question' model there. The previous one still has the default models.
How can I make the custom admin view with the right way?
Thanks.

It is solved. I am using my second admin.py and urls.py snippets and register django's default model, based on this answer: Django (1.10) override AdminSite
admin.py
from django.contrib.admin import AdminSite
from django.http import HttpResponse
from django.urls import path
from .models import Question
from django.contrib.auth.models import Group, User #add these moduls
from django.contrib.auth.admin import GroupAdmin, UserAdmin #and these
class CustomAdminView(AdminSite):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'my_view/', self.admin_view(self.my_view))
]
urls = my_urls + urls
return urls
def my_view(self, request):
return HttpResponse("Hello, world.")
custom_admin = CustomAdminView()
custom_admin.register(Question)
#register the default model
custom_admin.register(Group, GroupAdmin)
custom_admin.register(User, UserAdmin)

Related

my url in django doesn't return HTTPResponse?

there is a problem with a url i've created in django that it doesn't totally work
this is urls.py
from django.conf.urls import include, url
from django.contrib import admin
from pizza import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url('', views.home,name='home'),
url('order/', views.order,name='order'),
]
and this is views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Home page")
def order(request):
return HttpResponse("Order a pizza page")
That is incorrect syntax, try using path('') instead of url
If pizza it's your app you must use:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('pizza/', include('pizza.urls')),
]
in urls.py and add your app in settings.py inside INSTALLED_APPS
OR
If when you call from pizza import views is the name of Project you should import as import .views only
Update in project urls.py file.

Trying to trace a circular import error in Django Python

I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'

Custom templates for custom AdminSite Django

I have two admin sites and I want to have different custom templates on both of them
This is my admin.py file:
from django.contrib import admin
from django.contrib.admin import AdminSite
from .models import Equipo
#admin.register(Equipo)
class EquipoAdmin(admin.ModelAdmin):
list_display = ('codigo', 'nombre', 'contador', 'unidades')
class AdminMantenimiento(AdminSite):
site_header = "MANTENIMIENTO"
class EquipoAdminMantenimiento(admin.ModelAdmin):
list_display = ('codigo', 'nombre')
admin_site = AdminMantenimiento(name='Administrador Mantenimiento')
admin_site.register(Equipo, EquipoAdminMantenimiento)
This is my urls.py file:
from django.contrib import admin
from django.urls import path
from Mantenimiento.admin import admin_site
urlpatterns = [
path('admin/', admin.site.urls),
path('admin2/',admin_site.urls)
]
If I override the templates as per Django documentation changes would be applied to both AdminSites. How can I set custom templates for the class extending AdminSite?
The only way I could think to do this would be to explicitly override the url of the admin page you want to customize and point it to a different template. For example to customize a template in admin2/ but not admin1/
from django.contrib import admin
from django.urls import path
from Mantenimiento.admin import admin_site
from app.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('admin2/app/model', TemplateView.as_view(template_name='model_admin.html')),
path('admin2/', admin_site.urls)
]
This will only work if the more specific url definition (admin2/app/model) comes before the less specific definition (admin2/)

Error django: AttributeError: module 'django.contrib.auth.views' has no attribute 'Home'

I'm currently trying to implement the ability to login and logout into my django site and I'm getting the following error when attempting to use the command python manage.py runserver while in the virtual environment. I'm using django 2.2
my porject:
realtime
|-core
|-nodejs
|-realtime
|-templates
| |-index.html
|-url.py
my code url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'Home/$', views.Home, name='Home'),
url(r'^node_api$', views.node_api, name='node_api'),
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')),
url(r'^login/$', views.LogoutView.as_view(template_name=template_name), name='logout'),
]
core\views.py
from core.models import Comments, User
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseServerError
from django.views.decorators.csrf import csrf_exempt
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
import redis
#login_required
def home(request):
comments = Comments.objects.select_related().all()[0:100]
return render(request, 'index.html', locals())
#csrf_exempt
def node_api(request):
try:
#Get User from sessionid
session = Session.objects.get(session_key=request.POST.get('sessionid'))
user_id = session.get_decoded().get('_auth_user_id')
user = User.objects.get(id=user_id)
#Create comment
Comments.objects.create(user=user, text=request.POST.get('comment'))
#Once comment has been created post it to the chat channel
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.publish('chat', user.username + ': ' + request.POST.get('comment'))
return HttpResponse("Everything worked :)")
except Exception as e:
return HttpResponseServerError(str(e))
On the line
url(r'Home/$', views.Home, name='Home'),
the view Home is loaded from module views which refer to this import:
from django.contrib.auth import views
Since django.contrib.auth.views does NOT define any class or function Home, you get your error.
You probably forgot to import your app's views module:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
import core.views as my_app_views
urlpatterns = [
url(r'Home/$', my_app_views.home, name='Home'),
url(r'^node_api$', my_app_views.node_api, name='node_api'),
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')),
url(r'^login/$', auth_views.LogoutView.as_view(template_name=template_name), name='logout'),
]
Please note that in this new version, django.contrib.auth.views is imported with name auth_views and your custom app's views is imported with name my_app_views. This will prevent any confusion when calling views from one app or another

custom views within Djangocms?

I haven't found a satisfactory way of doing this: I have a djangocms setup that is working fine. But I need to add content from a table outside the CMS to my homepage and render that content on the template. I can do this, but editing the urls.py within CMS to use my views like so...
url(r'^', 'myapp.views.slideshow_info'),
... excludes any content from CMS. I understand that I just get my custom views to accommodate what CMS' views is doing, but how do I achieve this?
at the moment my app's views says:
from myapp.models import model1, model2
def slideshow_info(request):
return render_to_response('index.html', {'slideshow_list' : model1.objects.all()})
Many thanks
You can hook a custom app instance to any Django-CMS page. Here's the documentation on how to do so: http://docs.django-cms.org/en/2.1.3/extending_cms/app_integration.html#app-hooks You shouldn't need to alter the base url patterns to specifically re-route / to your view.
Before custom app-hooks were available, I would accomplish what you're trying to do with template tags.
Hope that helps you out.
Followup
Ok, in a recently completed site, I had to hook an app titled "portfolio" to display images on the home page of a Django-CMS site.
Here are the relevant portions of the code:
#portfolio/cms_app.py
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
class PortfolioAppHook(CMSApp):
name = _('Portfolio')
urls = ['portfolio.urls']
apphook_pool.register(PortfolioAppHook)
#portfolio/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('portfolio.views',
url(r'^(?P<slug>[-\w]+)/$', 'project_detail', name='project_detail'),
url(r'^$', 'portfolio_index', name='portfolio_index'),
)
#portfolio/views.py
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from portfolio.models import Project
def portfolio_index(request):
project_objects = Project.for_public if request.user.is_anonymous() \
else Project.objects
projects = project_objects.all().select_related(depth=1)
return render('portfolio/index.html',
{'projects' : projects}, request)
def project_detail(request, slug):
project = get_object_or_404(Project, slug=slug)
if not project.public and request.user.is_anonymous():
return HttpResponseRedirect('/?login=true')
return render('portfolio/project_detail.html',
{'project' : project}, request)
#urls.py (base urls)
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from views import login_user, logout_user
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/filebrowser/', include('filebrowser.urls')),
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
url(r'^login/$', login_user, name='login_user'),
url(r'^logout/$', logout_user, name='logout_user'),
(r'^', include('sorl.thumbnail.urls')),
(r'^', include('cms.urls')),
)
if settings.SERVE_STATIC_MEDIA:
urlpatterns += patterns('',
(r'^' + settings.MEDIA_URL.lstrip('/'), include('appmedia.urls')),
) + urlpatterns
As you can see from this working example, I haven't altered my base URLs to accommodate the home page view, rather I've provided the URLs for my Portfolio app to Django-CMS through cms_app.py
Hope that gets you going.

Categories