lang/python/ DjangoNotes001
First Django App
Following here at djanoproject.com
Install
In anaconda
conda install -c anaconda django
test: run this in an interactive shell and see if you get an error or not
import django
First app
django-admin startproject mysite
structure:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
python manage.py runserver
By default this uses port 8000
, but we can
python manage.py runserver 8080
python manage.py runserver 0.0.0.0:8080
Creating the app
python manage.py startapp polls
then in polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello World")
and in pools/urls.py
from django.urls import path
from . import views
urlpatterns - [
path('', views.index, name="index")
]
then in mysite/urls.py
(this is the master urls.py
for the whole project, whereas polls
is an app that lives within the project.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls'))
path('admin/', admin.site.urls),
]
you should always use include()
to include other URL patterns,
the exception being admin.site.urls
path()
path(route, view, kwargs, name)
# route -- url pattern
# view -- function to delegate to
# additional kwargs -- for the view function
# name -- give the route a name