Implementing Django Models and Templates for a Polling Application
Designing the Data Schema
A Poll model stores the main poll questions.
id: Primary key, auto-incrementing.poll_text: The question text, stored as aCharFieldwith a maximum length of 120 characters.created_at: The creation timestamp, stored as aDateTimeField.
An Option model stores the choices associated with each poll.
id: Primary key, auto-incrementing.poll: A foreign key linking to thePollmodel.option_text: The choice text, stored as aCharFieldwith a maximum length of 120 characters.votes: An enteger field to count votes, defaulting to 0.
Writing the Model Code
In polls/models.py, define the models:
from django.db import models
class Poll(models.Model):
poll_text = models.CharField('Poll Question', max_length=120)
created_at = models.DateTimeField('Created', auto_now_add=True)
def __str__(self):
return self.poll_text
class Option(models.Model):
poll = models.ForeignKey(Poll, verbose_name='Related Poll', on_delete=models.CASCADE)
option_text = models.CharField('Choice Text', max_length=120)
votes = models.PositiveIntegerField('Vote Count', default=0)
def __str__(self):
return self.option_text
Generating Database Tables from Models
First, activate the polls appliaction by adding it to INSTALLED_APPS in mysite/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig',
]
Then, create and run the database mgirations from the terminal:
python manage.py makemigrations
python manage.py migrate
Using the Model API
Interact with models in the Django shell:
# Create a new Poll
new_poll = Poll.objects.create(poll_text="What is your preferred IDE?")
# Retrieve a specific Poll by its primary key
poll_one = Poll.objects.get(pk=1)
# Retrieve all Poll objects
all_polls = Poll.objects.all()
# Access a field value
print(poll_one.poll_text)
Setting Up the Django Admin Interface
Create a superuser account:
python manage.py createsuperuser
Register the models in polls/admin.py to manage them via the admin site:
from django.contrib import admin
from .models import Poll, Option
# Inline display for Options within the Poll admin page
class OptionInline(admin.TabularInline):
model = Option
# Custom admin configuration for the Poll model
class PollAdmin(admin.ModelAdmin):
inlines = [OptionInline]
admin.site.register(Poll, PollAdmin)
admin.site.register(Option)
Start the development server and navigate to http://127.0.0.1:8000/admin/ to log in.
python manage.py runserver
Implementing Templates
Create a template directory. It can be organized centrally in the project (mysite/templates/polls/) or within the app (polls/templates/polls/). Ensure the template directories are configured in settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
Create a template file, for example polls/templates/polls/list.html, and populate it:
<ul>
{% for item in poll_list %}
<li>{{ item.poll_text }}</li>
{% endfor %}
</ul>
Creating a View to Render the Template
Update the view in polls/views.py to fetch data and render the template:
from django.shortcuts import render
from .models import Poll
def poll_list(request):
poll_list = Poll.objects.all()
context = {'poll_list': poll_list}
return render(request, 'polls/list.html', context)
This view retrieves all Poll objects, passes them to the template via a context dictionary, and returns the rendered HTML response.