m Build a webpage that displays “Hello World”
m Take a peek at Django views and URL configurations, which make up the Controller
m Remove an app
2.1
Introduction
The goal, when using the web framework, is to add code to the Model, View, and Controller sections to give life to the website you wish to build. I stated inChapter 1that every developer would need all three of these tools to build a functional website. However, a close look at Figure2.1shows that it is possible to build a website using only the Controller portion of Django.
In this chapter, we build a single webpage in Django using only the Controller (Chapter 5: Creating Webpages with Controllers in Django) to demonstrate that the diagram is technically correct. However, in doing so, we will see that the Model (Chapter 3: Programming Django Models and Creating a SQLite Database) and View (Chapter 4: Rapidly Producing Flexible HTML with Django Templates) portions of Django are crucial when building a full-features website, but we do not use them here.
Hello World, the traditional programming example, is typically quite short and simple in a programming language. Django is a framework, and building a webpage to display “Hello World” is a little more involved than it would be with a programming language. The goal is not to understand every detail but to get a first global view of the framework. It should seem a little magic.
24 Chapter 2 Hello World: Building a Basic Webpage in Django View Data Output Computer Data Input Django Website Controller Model Database User
Figure 2.1:Application of MVC Architecture Diagram
2.2
Creating and Integrating a New App
For the sake of time, we reuse our suorganizer project. For the sake of repetition, we create (and then destroy) a new app.
As seen inChapter 1, interacting with Django via the shell always starts with an invocation tomanage.py. We start by creating a new app, helloworld, using the startappcommand shown in Example 2.1.
Example 2.1:Shell Code
$ ./manage.py startapp helloworld
The file directory is exactly the same as for organizer and blog, as discussed in Chapter 1, Section 1.7.3. Just as before, we must now connect or integrate our app to our project. We append the name of our app to a list of installed apps in the project settings file. Open/suorganizer/settings.py, find the tuple of installed apps at line 33, and append the name of our helloworld app. The resulting code is shown in Example 2.2.
Example 2.2:Project Code
suorganizer/settings.pyin84b2c91a94 33 INSTALLED_APPS = ( 34 'django.contrib.admin', 35 'django.contrib.auth', 36 'django.contrib.contenttypes', 37 'django.contrib.sessions', 38 'django.contrib.messages',
2.3 Building Hello World 25 39 'django.contrib.staticfiles', 40 'organizer', 41 'blog', 42 'helloworld', 43 )
With our app created and integrated, we can now turn our attention to the Controller.
2.3
Building Hello World
InChapter 1, Section 1.2, we discussed how every website was originally a collection of webpages, each identified by a URL. Each webpage is thus two things: the data that the webpage contains and gives back to the user and the URL that identifies the webpage.
Django uses this construction to its advantage and splits the theoretical Controller into two parts. To build a webpage, we first need to define what data the webpage returns and then define the URL for the webpage.
2.3.1
Webpage Data
Webpage data are typically stored in theviews.pyfile of any app. This may seem confusing, given the Model-View-Controller architecture. For the moment, remember that Django views and MVC Views are unrelated concepts!
Open the file found at/helloworld/views.py. Erase the contents of the file and replace them with the code shown in Example 2.3.
Example 2.3:Project Code
helloworld/views.pyin9937ef66c0 1 from django.http import HttpResponse 2
3
4 def greeting(request):
5 return HttpResponse('Hello World!')
Our webpage is simply a Python function calledgreeting(). Given our understanding of HTTP request/response, we can already see how Django handles this for us. Django gives our function a request, which we ignore above, and we simply return a response, which Django then sends back to the user. Django termsgreeting()a function view (a Python function that fulfills the role of a Django view). In Example 2.3, our response is simplyHello World, as you should expect of this chapter.
2.3.2
Webpage URL
Now that our webpage has data, we must create a URL for it. InChapter 5, we see how to create URLs for each app separately. For the moment, however, we simply use the project-wide URL configuration.
26 Chapter 2 Hello World: Building a Basic Webpage in Django
To tell Django of the existence of the webpage created bygreeting(), we must make
changes to/suorganizer/urls.py. Open the file and import our new function by
addingfrom helloworld.views import greetingto the end of the import list,
just as you would import any Python function. We then direct Django to our webpage by
adding an item to theurlpatternslist. The argument we add isurl(r'ˆ$',
greeting). The contents of the file should now be as shown in Example 2.4.
Example 2.4:Project Code
suorganizer/urls.pyin98a8ef0d11
16 from django.conf.urls import include, url 17 from django.contrib import admin
18
19 from helloworld.views import greeting 20
21 urlpatterns = [
22 url(r'ˆadmin/', include(admin.site.urls)), 23 url(r'ˆ$', greeting),
24 ]
Info
If you open/suorganizer/urls.pyyourself, you will discover that the first 15 lines of the document provide instructions on how to build URLs. We’ve just used the first of these methods. We’ll see the rest inChapter 5.
Given the two-part nature of a webpage, it should seem natural that the call to url()has two arguments. The first is our URL, as a regular expression string, and the second is the webpage itself. For the moment, understand that we are using the regular expression to match nothing, the root of the website. If our website domain is
django-unleashed.com, then the URLhttp://django-unleashed.com/
will display ourgreeting()webpage. Stated differently, if a user requests
http://django-unleashed.com/, Django will useurlpatterns, the URL configuration above, to first find and then run thegreeting()function, returning its contents to the user as an HTTP response.
2.4
Displaying Hello World
With webpage data and URL defined, we can now see the fruits of our labor. In Example 2.5, we again turn tomanage.pyto make our life easy.
Example 2.5:Shell Code
2.6 Removing Our Helloworld App from Our Project 27
Warning!
If you did not run themigratecommand inChapter 1, Section 1.7.2, you must do so before you can invokerunserver, as shown in Example 2.6.
Example 2.6:Shell Code
$ ./manage migrate
Open your browser and navigate tohttp://127.0.0.1:8000/. Django will greet
you with “Hello World.” We have successfully created a single webpage using only MVC’s Controller.