Create App View
[courses/views.py]
from django.http import HttpResponse
from django.shortcuts import render
from .models import Course
def course_list(request):
courses = Course.objects.all()
output = ', '.join([str(course) for course in courses])
return HttpResponse(output)
.models
.
means look for the models
module in the current directory
join([str(course) for course in courses])
Join expects a list of strings. Thus, we needed to turn course types into strings before printing.
Add App URLs
[courses/urls.py]
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.course_list),
]
Now, if you test the homepage, you’ll still see the “Hello, world!” line from last time.
That’s because we need to add the app’s URL list to the project’s URL list.
python manage.py runserver 0.0.0.0:8000
Add App URLs to Project URLs
[urls .py] (i.e. learning_site/urls.py)
...
urlpatterns = [
url(r'^courses/', include('courses.urls')),
url(r'^admin/', include('admin.site.urls')),
url(r'^$', views.hello_world),
]
...
include()
A function that lets us include a set of URL patterns from somewhere else.
In our case, URL patterns from our Courses app.
'courses.urls'
A string. Django turns this string into an import path, which lets it find the URL patterns.