Custom admin interface in Django - django

Django's documentation provides an easy way of installing admin app.
It assumes the structure of files as follows:
mysite/
manage.py
mysite/
settings.py #adding `admin` under `INSTALLED_APPS`
__init__.py
urls.py #adding urls
wsgi.py
myapp/
__init__.py
admin.py #creating this file
models.py
views.py
My question is how to get the admin interface to work if my structure is as follows:
mysite/
manage.py
settings.py
__init__.py
urls.py
myapp/
__init__.py
forms.py
models.py
views.py
What will be the various changes that I will have to incorporate to get the admin interface working. [my other apps are working].
I have read and read the documentation several times.
I'm using Django 1.4.
EDIT#1
I'm getting this error on running localhost:8000/admin/:
error at /admin/
unknown specifier: ?P[
Whole error here.
My urls.py file has the lines [as in the docs]:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', include(admin.site.urls)),
)
My admin.py file in the myapp folder has the code:
import models
from django.contrib import admin
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(models.Article, PostAdmin)

This is how you're supposed to include the admin urls:
url(r'^admin/', include(admin.site.urls)),
The documentation shows this.
The error that you're getting is coming straight from the re python module, complaining about this part of a url:
?P[
The URLs you've posted in your comment beneath show this:
url(r'^(?P[-a-zA-Z0-9]+)/?$', 'myapp.views.getPost')
Try changing that url by giving the match group a name:
url(r'^(?P<slug>[-a-zA-Z0-9]+)/?$', 'myapp.views.getPost')
And in your getPost view, include a slug argument.

Related

How to create href link from one Django app to another

I know this has been asked multiply times before, but I still don't get it.
How can I create a href-link in one Django app that sends the user to a 2nd app?
This is my setup:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
app1/
migrations/
templates/
app1/
app1.html
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
app2/
migrations/
templates/
app2/
app2.html
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls'), name='app1'),
path('app2/', include('app2.urls'), name='app2'),
]
myproject/settings.py
INSTALLED_APPS = [
'app1.apps.App1Config',
'app2.apps.App2Config',
'django.contrib.admin',
...
]
app1/urls.py (analogous for app2)
from django.urls import path
from . import views
urlpatterns = [
path('', views.app1, name='app1'),
]
app1/views.py (analogous for app2)
from django.template import loader
from django.http import HttpResponse
def app1(request):
template = loader.get_template('app1/app1.html')
return HttpResponse(template.render())
app1/templates/app1/app1.html (analogous for app2)
<p>This is the template of app1.</p>
Go to App2 # doesn't work
Go to App2 # doesn't work
Go to App2 # doesn't work
My problem is that this sends me to the address 127.0.0.1:8000/app1/app2/ which gives me a 404 error. However, I can access app2 via 127.0.0.1:8000/app2/ without a problem.
Edit:
Thanks everyone for your feedback. After going through your suggestions, I made the following changes:
myproject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls', namespace='app1')), # ADDED NAMESPACE
path('app2/', include('app2.urls', namespace='app2')), # ADDED NAMESPACE
]
myproject/settings.py: no changes
app1/urls.py: (analogous for app2)
from django.urls import path
from . import views
app_name = 'app1' # THIS WAS MISSING
urlpatterns = [
path('', views.app1, name='app1'),
]
app1/views.py: no changes
app1/templates/app1/app1.html: (analogous for app2)
<p>This is the template of app1.</p>
Go to App2 # AS SUGGESTED BY seif
Now it works.
in your template and views try not to hardcode the url of href instead use the {%url ''%}
which will be {%url 'namespace:urlname'%}
<p>This is the template of app1.</p>
Go to App2
this give you flexibility to change the path in your urls and not to worry about changing it at all your templates and views you can read more here https://docs.djangoproject.com/en/3.1/topics/http/urls/#reverse-resolution-of-urls
your href link doesn't go to the .html file in templates, templates are just for UI, and barely have a say in how you project gets routed, infact it depends on you to configure. instead it should go to the url specified in your url file,
so say your bases url is
path('app1/', include('app1.urls'), name='app1')
for one of your app it will be
App 1
if you have other links under app1 url file, it will then be
A link under App 1
example.com here, could be localhost:8000 or just localhost with any port, depending on the port your django project runs one.
then as for this,
from django.template import loader
from django.http import HttpResponse
def app1(request):
template = loader.get_template('app1/app1.html')
return HttpResponse(template.render())
I will suggest you do something like this instead
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
def app1(request,slug=None):
return render(request,'app1/app1.html',{})
#path to the template folder, under templates, depends on your configuration though
Kindly read more on templates configuration and routing in Django,but this should give a jumpstart.
Cheers
When you input "127.0.0.1:8000/app1/app2/", django will recieve "app1/app2/" and work like below(not accurate):
1.compare app1/ to every element in urlpatterns of myproject/urls.py
so, app1/ will be found.
2.compare app2/ to every element in urlpatterns of app1.urls
there's nothing will be found, because there is only a "" in urlpatterns of app1.urls.
so you get a 404 page.
if you input "127.0.0.1:8000/app2/", in step 2, "" equals to "",
fuction views.app2 executes, and you get a correct page.
I suggest you read the django's tutorials in official site.
https://docs.djangoproject.com/en/3.1/intro/tutorial01/

Page not found error - Writing your first Django app, part 1

I have installed Django 2.2.5 in my conda environment and I'm following the Django tutorial for Writing your first Django app, part 1
I followed the steps exactly but I'm getting a Page Not Found error when I try to access the polls/ url.
My root directory structure is like this
mysite/
manage.py
db.sqlite3
urls.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
polls/
migrations/
__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
And my view is like this
D:\TEMP\djangotest\mysite\polls\views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello World. You're at the polls index")
My two urls files are like this
D:\TEMP\djangotest\mysite\polls\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
D:\TEMP\djangotest\mysite\urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
And I run the app from the environment like this
(py3.6) D:\TEMP\djangotest\mysite>python manage.py runserver
But when I go to the url indicated in the tutorial it give the 404 error - page not found from the console
October 21, 2019 - 16:23:13
Django version 2.2.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Not Found: /polls
[21/Oct/2019 16:23:19] "GET /polls HTTP/1.1" 404 1954
From the browser it look like
Page not found (404)
Request Method:
GET
Request URL:
http://localhost:8000/polls
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
The current path, polls, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Your main urls file is in the wrong directory. It looks like you've created a separate urls.py in the base "mysite" directory; instead you should have edited the existing one in the "mysite/mysite" directory. The one you've created isn't being used at all.

grappelli dashboard ValueError on two admin sites

I want use two admin sites for my project. Each with grappelli dashboard. I've executed this commands:
python manage.py customdashboard dashboard.py
python manage.py customdashboard dashboard.py
twice (once in project/project and second time in project/app)
#file system
project
project
dashboard.py
urls.py
app
dashboard.py
admin.py
#settings.py
GRAPPELLI_INDEX_DASHBOARD = {
'django.contrib.admin.site': 'project.dashboard.CustomIndexDashboard',
'app.admin.operator_site': 'app.dashboard.CustomIndexDashboard',
}
#urls.py
from django.conf.urls import patterns, url, include
from django.contrib import admin
from app.admin import admin_site
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^myadmin/', include(operator_site.urls)),
url(r'^grappelli/', include('grappelli.urls')),
)
#app/admin.py
from django.contrib.admin import AdminSite
class MyAdminSite(AdminSite):
pass
admin_site = MyAdminSite()
The problem is when I go to /admin/ everything is ok, but when I go to /myadmin/ , I've got ValueError
Dashboard matching "{'app.admin.operator_site': 'app.dashboard.CustomIndexDashboard', 'django.contrib.admin.site': 'project.dashboard.CustomIndexDashboard'}" not found
full error trace: http://pastebin.com/w8W2eRPd
Where is the problem?
Ok, i've found it out. When making a subclass of a AdminSite on make an instance
admin_site = MyAdminSite()
you should use a custom name parameter (not 'admin'):
admin_site = MyAdminSite(name='myadmin')

ImportError After Moving App to Nested Folder

My application was working fine when I wanted to see whether I could organize my project in a better way. I read through this tutorial on structuring a django project.
Before my project structure was as follows:
camucamu
books
admin.py
models.py
views.py
__init__.py
static
templates
urls.py
views.py
settings.py
wsgi.py
__init__.py
What I wanted to do was move the books app into an apps folder. Thus I did that and changed the project structure to the following:
camucamu
apps
books
admin.py
models.py
views.py
__init__.py
static
templates
urls.py
views.py
settings.py
wsgi.py
__init__.py
I then changed the imports in views.py and admin.py
from books.models to apps.books.models.
I also changed INSTALLED_APPS in settings.py from books to apps.books.
When I then tried to run syncdb, I get the following error:
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
django.core.exceptions.ImproperlyConfigured: ImportError apps.books: No module named apps.books
What am I messing up here so it can't find my app anymore?
Your apps folder does not have an __init__.py file so it cannot be recognized as a python module
I got the same error, following the same guide, as the last point of the following list was not cited. Make sure you performed the following changes:
Create a blank __init__.py file inside the apps folder (needed for python to recognize it as a package)
Update the import statements wherever you refer to an external app:
from projectname.apps.appname.models import YourModel, YourOtherModel
Inside settings.py edit INSTALLED_APPS such that it looks like this:
INSTALLED_APPS = (
...
# apps
'projectname.apps.appname1',
'projectname.apps.appname2',
)
This one is not specified in the guide: In all your urls.py files, update the urlpatterns!
BEFORE:
# client views
urlpatterns += patterns('appname',
...
)
AFTER:
# client views
urlpatterns += patterns('projectname.apps.appname',
...
)
Finally remember to update your changes by calling python manage.py syncdb
Hope that helped.

Django App URL model not importing

Im certain that this is something simply that Im overlooking but Im too irritated to figure it out alone so thanks in advance.
Project Directory Structure
*UPDATED*
myproject/
manage.py
myproject/
apps/
geo/
urls.py
settings.py
urls.py
urls.py
from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.gis import admin
admin.autodiscover()
from pinax.apps.account.openid_consumer import PinaxConsumer
handler500 = "pinax.views.server_error"
urlpatterns = patterns("",
url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
url(r"^admin/invite_user/$", "pinax.apps.signup_codes.views.admin_invite_user", name="admin_invite_user"),
url(r"^admin/", include(admin.site.urls)),
url(r"^about/", include("apps.about.urls")),
url(r"^account/", include("pinax.apps.account.urls")),
url(r"^openid/", include(PinaxConsumer().urls)),
url(r"^profiles/", include("idios.urls")),
url(r"^notices/", include("notification.urls")),
url(r"^announcements/", include("announcements.urls")),
url(r"^products/", include("products.urls")),
url(r"^locate/", include("geo.urls")),
url(r"^sectors/", include("sectors.urls")),
)
if settings.SERVE_MEDIA:
urlpatterns += patterns("",
url(r"", include("staticfiles.urls")),
)
settings.py
INSTALLED_APPS = [
# project
"tulsa-site.apps.about",
"tulsa-site.apps.profiles",
"tulsa-site.apps.geo",
"tulsa-site.apps.sectors",
]
When I go to the url path "http://127.0.0.1:8000/locate/" is receive the error message: I recieve the exception value "No module named geo.urls." What am I missing?
include("geo.urls") tells Django to look for geo.urls relative to the manage.py file. So its essentially looking for this file:
myproject/
manage.py
myproject/
apps/
settings.py
urls.py
geo/
urls.py <- this file
That is sort of the new directory structure starting with Django 1.4 which encourages to have apps independent of the Django project. However if you still follow the old layout where the apps folders are within the project folder, then you have to change your imports to reflect that:
include("myproject.geo.urls")
EDIT
Following your updated layout:
include("myproject.apps.geo.urls")
url(r"^locate/", include("tulsa-site.apps.geo.urls"))