In the previous entry we saw a theoretical approach to Django. We now set to create a first simple Django “Hello World” app. This app will just return a random Simpsons quote when we access a certain URL. This will help to see how to set up and configure the Django environment.
We must start installing the Django package if it is not already in our system. We do that with pip install django. This will automatically download all the dependencies.
Next, we must choose where to create the project that will contain our app, and optionally related apps. We navigate to the directory using a terminal (CMD in Windows), and create the project:
django-admin startproject SQproject
This will create a new directory that contains some important files. manage.py is the script that we will use to manage our project (for creating apps, running the server, etc). The SQproject directory contains some settings files, the main one being settings.py. By now, we will leave everything with the default configuration. We will come back to settings.py to change things such as the database backend, middleware applications (for the Django REST framework) and so on. The urls.py file contains the mappings between URLs and views.
We can now create an app in the project by running python manage.py startapp SQapp. This will create a new directory called SQapp. Several files are created in this directory, but by now we only need to know models.py (that contains the classes representing the data managed by the app) and views.py (that contains the functions that manage the requests of the clients).
The first step is to create the models. Since this application has a very simple data model (quotes), the content of models.py is very simple:
from django.db import models class SimpsonQuote(models.Model): content = models.TextField() character = models.CharField(max_length=100) season = models.IntegerField() episode = models.IntegerField()
The class inherits from models.Model, and has four properties: content and character, that are strings, and season and episode that are integer fields.
Once the app is created, we edit settings.py. We must find the declaration of a list called INSTALLED_APPS, and add an element so it looks something like this:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'SQapp', ]
With this model, we can start populating the database, but first, we must create it! We go back to the terminal and run python manage.py migrate. After the database is created (in a SQLite file called db.sqlite3), we must populate it. We can do this in several ways; either by the admin interface (in that case, create a user with python manage.py createsuperuser and read on until we run the server), or by starting a Python terminal with specially preloaded configurations by running python manage.py shell. Once in the shell, we execute the following commands:
>>> from SQapp.models import SimpsonQuote >>> q1 = SimpsonQuote(content="I, for one, welcome our new insect overlords.", character="Kent Brockman", season=5, episode=15) >>> q1.save() >>> q2 = SimpsonQuote(content="You tried your best and you failed miserably. The lesson is: Never try.", character="Homer Simpson", season=5, episode=18) >>> q2.save() >>> q3 = SimpsonQuote(content="Don't blame me, I voted for Kodos.", character="Homer Simpson", season=8, episode=1) >>> q3.save() >>> q4 = SimpsonQuote(content="My cat's breath smells like cat food.", character="Ralph Wiggum", season=6, episode=2) >>> q4.save() >>> q5 = SimpsonQuote(content="Life is just one crushing defeat after another until you just wish Flanders was dead.", character="Homer Simpson", season=5, episode=13) >>> q5.save() >>> quit()
We now have some data to serve… so lets serve it! We now must create a view, so we edit SQapp/views.py with the following content:
from django.http import HttpResponse from SQapp.models import SimpsonQuote def randomquote(request): quote = SimpsonQuote.objects.order_by('?').first() response = '\"' + quote.content + '\" ' + quote.character + ' (S' + str(quote.season) + 'E' + str(quote.episode) + ')' return HttpResponse(response)
The view first randomly selects one entry. We import SimpsonQuote and use the Django ORM to access to the entries (objects). We order randomly and take the first entry. Afterwards, we extract each field and use it to populate a string. Finally we create an HttpResponse with the content of the string, and return it (i.e: we send it to the client). In this case, we have not used the contents of the request (more on that in future entries).
We must now make this view accessible from the outside world by assigning it a URL. We edit the SQproject/urls.py file and edit it so it looks like this:
from django.conf.urls import url from django.contrib import admin from SQapp.views import randomquote urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^randomquote/', randomquote), ]
We import the view and add a line to urlpatterns to assign the randomquote/ URL to the view. There is a previously assigned URL to another view. This url corresponds to the admin interface.
That’s it! We now must start the Django development server by going to the terminal and running python manage.py runserver. The server will start usually on port 8000. So we fire up a web browser and access http://127.0.0.1:8000/randomquote/ to get our random Simpsons quote.
This was a rather simple application; but enough to get a sense of how to start a project and add the basic components. The Django tutorial walks through the whole process more slowly and with more detail. In the next entry we will add some interaction with the client, by reviewing more in-depth the concept of requests.