Polls Application
This week I created a polls application in Django. It uses a data base to store questions and choices and then displays the results on a separate page. I have also created an admin page in which I can access the database and make changes. Please go to jpernick.pythonanywhere.com/polls to see it in action and vote on the next platform you'd like to see me use.*Please click on the photos to enlarge them.
Creating the polls directory
I created the polls directory the same way I created the hello app in the last blog post, with the command 'python manage.py startapp polls'. This is what we created:
For this app, I created two models, a question and a choice. Each choice is associated with a question. These are located in the polls/models.py file:
Next I ran a few commands into a bash console. By running 'python manage.py makemigrations polls' it creates migrations for the changes made to models.py. Next I ran 'python manage.py migrate' to apply those changes to the database.
Updating the database and creating the admin page
There are two different ways to update the database. One way is by using the command 'python manage.py shell' This opens up the python interactive shell:
You can run a number of commands in this shell that will manipulate and display data.
.objects.all() - will show all of the objects
.objects.filter(id=1) - will filter results to show the question with id =1
q.choice_set.create(choice_text = "example", votes = 0) - will create a choice related to the question
Another way to update the database is through creating an admin page. First I ran the command 'python manage.py createsuperuser' and was prompted to give my desired username and password. I can now reach the admin page for the site at jpernick.pythonanywhere.com/admin and after logging in I can see this page:
Now I can click on the change button and make changes to the database:
In order to make the question data accesible on this page I updated the polls/admin.py page to look like this:
from django.contrib import admin
from .models import Question
admin.site.register(Question)
Views, urls, templates
I made three templates to hold the html code for each of the web pages. But before I updated these I had to update the polls/views.py file:
index.html
details.html
results.html
This code connects the views to each of the templates. It also contains what to do when someone votes in the poll or if they try to submit a vote without selecting a choice. The polls/urls.py contains the code to make a call to the view to show in the browser:
Next I updated each of the templates found in mysite/polls/templates/polls/ :
Thank you for reading!! Please comment what you would like to see next and don't forget to go to jpernick.pythonanywhere.com/polls to vote in the poll!
-Joe
No comments:
Post a Comment