Building a Simple Django Application

Follow the steps below to implement a simple “online survey” program in Django. These instructions are a simplified form of a tutorial found on the official Django website at the URL “https://docs.djangoproject.com/en/1.8/intro/tutorial01/“, with much of the explanatory discussion (and digression) removed.

SurveyQuestionResults

1. Download and install Python. Python is the programming language in which Django is implemented. As of this writing, the most recent version is available at the URL “https://www.python.org/downloads/“.

2. In any convenient location, create a new directory named “DjangoTest”.

3. Open a command prompt window and navigate to the newly created DjangoTest directory.

4. Still at the command prompt, run the command “pip install Django”. “Pip” is the package manager program for Python, and Django is a free and open source web application framework. Wait for Django to finish installing.

5. Still at the command prompt, run the command “django-admin startproject DjangoTestProject” and wait for the operation to complete. A new directory named “DjangoTestProject”, which contains multiple files and subdirectories, will be created within the DjangoTest directory.

6. Still at the command prompt, run the command “python DjangoTestProject/manage.py migrate” and wait for the operation to complete. The project’s database will be updated with with the data required to support the default set of Django applications.

7. Still at the command prompt, run the command “python DjangoTestProject/manage.py runserver”. A status messages will appear stating that the development server has been started.

8. Open another command prompt window, leaving the first running. Within the new command prompt window, navigate to the “DjangoTest/DjangoTestProject” directory, then run the command “python manage.py startapp AppTest” and wait for the operation to complete. A new directory named “AppTest” will be created.

9. Open the newly created AppTest directory in a file explorer. Within it, locate a file named “models.py”, open it in a text editor, replace its existing contents with the following text, and save the modified file.

from django.db import models

class Question(models.Model):
	question_text = models.CharField(max_length=200)
	pub_date = models.DateTimeField('date published')

	def __str__(self):
		return self.question_text

class Choice(models.Model):
	question = models.ForeignKey(Question)
	choice_text = models.CharField(max_length=200)
	votes = models.IntegerField(default=0)

	def __str__(self):
		return self.choice_text

10. Within the “DjangoTest/DjangoTestProject/DjangoTestProject” folder, locate the file named “settings.py”. Open the file in a text editor. Locate the section starting with the line “INSTALLED_APPS =(” and replace its existing contents with the following text. This change adds “AppTest” to the list of installed applications.

INSTALLED_APPS = (
	'django.contrib.admin',
	'django.contrib.auth',
	'django.contrib.contenttypes',
	'django.contrib.sessions',
	'django.contrib.messages',
	'django.contrib.staticfiles',
	'AppTest',
)

11. Back in the command prompt window, run the command “python manage.py makemigrations AppTest” and wait for it to complete. A few status messages will be displayed.

12. Still at the command prompt, run the command “python manage.py migrate” and wait for the operation to complete. The database will be updated with the data required to support the AppTest application, and a few status messages will be displayed.

13. Still at the command prompt, run the command “python manage.py createsuperuser” and supply the desired username, email address, and password when prompted. A new administrator user will be created with the specified credentials.

14. In the “AppTest” directory, locate the file named “admin.py”, open it in a text editor, replace its existing contents with the text shown below, and save the modified file.

from django.contrib import admin

from .models import Choice, Question

class ChoiceInline(admin.TabularInline):
	model = Choice
	extra = 3

class QuestionAdmin(admin.ModelAdmin):
	list_display = ('question_text', 'pub_date')
	fieldsets = [
		(None, {'fields': ['question_text']}),
		('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
	]
	inlines = [ChoiceInline]

admin.site.register(Question, QuestionAdmin)

15. Open a web browser and navigate to the URL “http://localhost:8000/admin/“. The administrator login page will appear. Enter the username and password specified in the previous step and click the “Log in” button. The main Django Administration page will appear.

16. On the main Django Administration page, click the “Questions” link. A page that lists all the Question objects in the application will appear. Initially, the list of Questions will be empty.

17. On the Question page, click the “Add question” button. The “Add question” page will appear.

18. On the “Add question” page, enter the text “What’s the word?” in the “Question text” box. Click the Show link in the “Date information” group box to expand it, then click the “Today” and “Now” links next to the Date and Time boxes to automatically populate them with the current date and time. In the three “Choice text” boxes, enter the values “Thunderbird”, “Stormcrow”, and “Blitzvogel”. Finally, click the “Save” button to save the new Question. The Question list page will reappear, and a new item labelled “What’s the word?” will appear in the list.

19. In the “AppTest” directory, locate the file “views.py” and open it in a text editor. Replace its existing contents with the following text.

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse

from .models import Choice, Question

def index(request):
	latest_question_list = Question.objects.order_by('-pub_date')[:5]
	context = {'latest_question_list': latest_question_list}
	return render(request, 'AppTest/index.html', context)

def detail(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
	return render(request, 'AppTest/detail.html', {'question': question})

def results(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
	return render(request, 'AppTest/results.html', {'question': question})

def vote(request, question_id):
	p = get_object_or_404(Question, pk=question_id)
	try:
		selected_choice = p.choice_set.get(pk=request.POST['choice'])
	except (KeyError, Choice.DoesNotExist):
		# Redisplay the question voting form.
		return render(request, 'detail.html', {
			'question': p,
			'error_message': "You didn't select a choice.",
		})
	else:
		selected_choice.votes += 1
		selected_choice.save()
		# Always return an HttpResponseRedirect after successfully dealing
		# with POST data. This prevents data from being posted twice if a
		# user hits the Back button.
		return HttpResponseRedirect(reverse('results', args=(p.id,)))

20. Still in the AppTest directory, create a new text file named “urls.py” containing the following text.

from django.conf.urls import url

from . import views

urlpatterns = [
	url(r'^$', views.index, name='index'),
	url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
	url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
	url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

21. Navigate to the “DjangoTestProject/DjangoTestProject” directory, locate the file “urls.py” within it, and open that file in a text editor. Replace its existing contents with the following text.

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
	url(r'^AppTest/', include('AppTest.urls')),
	url(r'^admin/', include(admin.site.urls)),
]

22. In the AppTest directory, create a new directory named “templates”. Within the newly created “templates” directory, create another directory named “AppTest”. Finally, within the newly created “AppTest” directory, create a new text file named “index.html”, containing the following text:

{% if latest_question_list %}
	<ul>
	{% for question in latest_question_list %}
	<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
	{% endfor %}
	</ul>
{% else %}
	<p>No polls are available.</p>
{% endif %}

23. In the same directory as the newly created file “index.html”, create another new text file named “detail.html”, containing the following text.

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
	<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
	<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

24. In the same directory as the newly created file “detail.html”, create yet another new text file named “results.html”, containing the following text.

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
	<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'detail' question.id %}">Vote again?</a>

25. Open the file “settings.py”, locate the section starting with the line “TEMPLATES = [“, replace it with the following text, and save the modified file. This change adds a value in the “DIRS” tuple, which allows Django to find the template directory.

TEMPLATES = [
	{
		'BACKEND': 'django.template.backends.django.DjangoTemplates',
		'DIRS': [
			os.path.join(os.path.realpath(os.path.dirname(__file__)), 'templates'),
		],
		'APP_DIRS': True,
		'OPTIONS': {
			'context_processors': [
				'django.template.context_processors.debug',
				'django.template.context_processors.request',
				'django.contrib.auth.context_processors.auth',
				'django.contrib.messages.context_processors.messages',
			],
		},
	},
]

26. Open a web browser and navigate to the URL “http://localhost:8000/AppTest“. A list of all the survey questions in the system will appear. If the instructions have been followed exactly, currently there should be only a single question: “What’s the word?”. Click on the link for that question. A list of choices for that question will appear.

27. On the voting page, click one of the radio buttons to select the desired choice, then click the Vote button to confirm the vote. The results page will appear, and the number of times each choice has been selected will be displayed. Click the “Vote again?” link to return to the voting page, then vote again. Repeat as many times as desired to verify that the vote totals are being tracked correctly.

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s