custom views within Djangocms? - python

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.

Related

How to Change Django Default Page to your Design?

I uploaded my site to the live server, but still, I am seeing Django default page, I updated my urls.py file, but still, it's not working. and it's showing me this output. Please let me know where I am Mistaking.
I am trying to access this mydomain.com/dashboard
Using the URLconf defined in yoursite.urls, Django tried these URL patterns, in this order:
admin/
The current path, dashboard, didn't match any of these.
here is my urls.py file...
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^dashboard/', include('dashboard.urls')),
url(r'^accounts/', include('accounts.urls')),
url('', include('frontpanel.urls')),
path('', views.index, name='index'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And here is my views.py file...
def index(request):
category = Category.objects.all().order_by('created_at')
return render(request, "base.html", {'category':category})
What version of Django are you using?
Try changing url to re_path (remember to import it first). I think url has been deprecated.
After Analyzing the question u never mentioned ur app urls.py you only mentioned project urls.py . As u have url(r'^dashboard/', include('dashboard.urls')), in ur project urls.py, there must be a file in your app also named urls.py which handles urls having prefix /dashboard/ , by default django doesnt make that file you need to manually make it add ur function names to redirect . For example this is my main urls.py file
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('display_report/', include("display_report.urls"))
]
then u have to make a file named urls.py in ur app also to handle the requests and redirect the the approaite functions , in my display_report app i made a urls.py that looks like this
from django.contrib import admin
from django.urls import path, include
from display_report import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [path('', views.index)]
And then it will redirect to function named index in ur views.py file inside ur app
from django.shortcuts import render, redirect, HttpResponse
# from .models import Employee, Tasks, Report, Fileupload, Fileuploadnext
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
def index(request):
return render(request."index.html")
Here my ur will be mydomain.com/display_report and my index.html file will be inside the template folder

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.

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

Mix Django and DRF urls

So far, I have built a REST API with Django Rest Framework (DRF) which can be consumed by any front-end. Let call this API backend.
I am trying to add another Django app (a regular one this time i.e. no DRF) which shares the same models. Let call this app webapp
However, it seems that the URLs linked to webapp are not available.
Here is my urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken import views as token_views
from backend import views
from webapp import views as webapp_views
router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet, 'User')
router.register(r'games', views.GameViewSet, 'Game')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'membership_create/', views.MembershipCreate.as_view()),
url(r'auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
url(r'^test/', webapp_views.home, name='test'), # the new view
)
]
urlpatterns += router.urls
And the single view (from webapp.views):
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return HttpResponse("""
<h1>WEBAPP !</h1>
<p>test webapp</p>
""")
I am thus wondering if DRF and regular Django views can be mixed so easily or if it is not the right way of doing it.
EDIT:
Using the URLconf defined in WMC.urls, Django tried these URL patterns, in this order:
^admin/
^connect/
membership_create/
auth/connect_with_fb/
auth/connect_with_credentials/
debug/
^auth/
^users/$ [name='User-list']
^users/(?P<pk>[^/.]+)/$ [name='User-detail']
^users/(?P<pk>[^/.]+)/games/$ [name='User-games']
^games/$ [name='Game-list']
^games/(?P<pk>[^/.]+)/$ [name='Game-detail']
The current URL, test/, didn't match any of these.
Moving url(r'^test/', webapp_views.home, name='test') before url(r'^admin/', admin.site.urls) solves the problem although I do not know why.
urlpatterns = [
url(r'^test/', webapp_views.home, name='test'),
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'^membership_create/', views.MembershipCreate.as_view()),
url(r'^auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'^auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'^debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
)
]

Django reporting 404 error on simple view?

I'm just barely getting started with Python and Django.
I've created my modules, migrated, added my modules to the admin section, etc. Now, I need to create my first view. I've been following this guide (Yes the machine I'm on is running 1.6)
My views.py file in the app (setup) looks like this...
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Setup Index")
My app'a urls.py looks like this...
from django.conf.urls import patterns, url
from setup import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
And my root urls.py looks like this...
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from django.conf.urls import include, patterns, url
from django.contrib import admin as djangoAdmin
from admin.controller import ReportWizard
from admin.forms import reportDetailsForm, reportDataViewsForm
from setup import views
djangoAdmin.autodiscover()
urlpatterns = patterns('',
url(r'^django-admin/', include(djangoAdmin.site.urls)),
#New User Wizard URL
url(r'^setup/', include('setup.urls')),
)
As far as I can tell I have followed the guide to the letter, but I am recieving a 404 error when navigating to myIP/setup.
There are no error messages on the 404 page. What is the issue?
For some reason your settings seem to override the default for either APPEND_SLASH or MIDDLEWARE_CLASSES.
Opening http://example.com/setup should cause a redirect to http://example.com/setup/, but somehow it doesn't for you.
Note that the latter URL is matched by your urls.py while the former is not (as should be the case).
The above should work if 'CommonMiddleWareis enabled andAPPEND_SLASHis set toTrue`.

Categories