Basic Django Hello World
By now, you should now have a basic django skeleton site as shown in Starting Django.
Here's how you create a basic site that now says "Hello World"
Create the App
Inside your basic skeleton site, run the command:
1~$ python3 manage.py startapp myapp
Server file structure of current directory would now be as follows:
1db.sqlite3
2manage.py
3myapp/ ## << new app
4mysite/
5mysite/__init__.py
6mysite/asgi.py
7mysite/settings.py
8mysite/urls.py
9mysite/wsgi.py
Add App to Installed Apps
Edit the file mysite/settings.py like below:
1INSTALLED_APPS = [
2 'django.contrib.admin',
3 'django.contrib.auth',
4 'django.contrib.contenttypes',
5 'django.contrib.session',
6 'django.contrib.messages',
7 'django.contrib.staticfiles',
8 'myapp', ## << add it here
9]
Create template files
1db.sqlite3
2manage.py
3myapp/
4myapp/templates/ ## << here (create)
5myapp/templates/myapp/ ## << here (create)
6myapp/templates/myapp/index.html ## << here (create)
With content of index.html as follows:
1<b>Hello World!</b>
Create Views
In myapp/views.py, add an "index" function:
1db.sqlite3
2manage.py
3myapp/
4myapp/views.py ## << here
as follows:
1from django.shortcuts import render
2
3def index(request): ## << here
4 return render(request, 'myapp/index.html')
Add homepage path
In mysite/urls.py, add the "index" path to urlpatterns list:
1db.sqlite3
2manage.py
3mysite/
4mysite/urls.py ## << here
as follows:
1from django.contrib import admin
2from django.urls import path
3
4from myapp import views as myapp_views ## << here
5
6urlpatterns = [
7 path('admin/', admin.site.urls),
8 path('', myapp_views.index, name='index'), ## << here
9]
Run server
1python3 manage.py runserver
Visit http://127.0.0.1:8000 or whatever is shown after running the server. Expect to see the "Hello World".