<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ashley Obano</title>
    <description>The latest articles on DEV Community by Ashley Obano (@ashley_obano_71cd63fedc66).</description>
    <link>https://dev.to/ashley_obano_71cd63fedc66</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2080074%2Fe0013041-dc95-4702-99a0-6e678ed196ff.png</url>
      <title>DEV Community: Ashley Obano</title>
      <link>https://dev.to/ashley_obano_71cd63fedc66</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ashley_obano_71cd63fedc66"/>
    <language>en</language>
    <item>
      <title>Setting Up Django and Building a Poll App: My Last Two Weeks of Work</title>
      <dc:creator>Ashley Obano</dc:creator>
      <pubDate>Mon, 16 Sep 2024 19:13:12 +0000</pubDate>
      <link>https://dev.to/swahilipotdevs/setting-up-django-and-building-a-poll-app-my-last-two-weeks-of-work-16jl</link>
      <guid>https://dev.to/swahilipotdevs/setting-up-django-and-building-a-poll-app-my-last-two-weeks-of-work-16jl</guid>
      <description>&lt;p&gt;Over the past two weeks, I've been working on setting up Django from scratch and building a simple poll application. This article will walk you through everything I did, starting from installing Python and Django, setting up a virtual environment, creating a new project, and building a functional app called polls.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Setting Up Python and Django&lt;/strong&gt;&lt;br&gt;
To begin, I made sure that Python was installed on my system. If you haven't installed it yet, you can download it from python.org.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install Python and Set Up a Virtual Environment&lt;/strong&gt;&lt;br&gt;
I wanted to keep my project dependencies isolated, so I used a virtual environment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Install virtualenv if you don't have it
pip install virtualenv

# Create a virtual environment
virtualenv myenv

# Activate the environment
# On Windows:
myenv\Scripts\activate
# On macOS/Linux:
source myenv/bin/activate

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Install Django&lt;/strong&gt;&lt;br&gt;
Once the environment was activated, I installed Django.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install django

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I then confirmed the installation by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin --version

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Starting a New Django Project: mysite&lt;/strong&gt;&lt;br&gt;
Now, it was time to create my Django project. I decided to call it mysite.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startproject mysite
cd mysite

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This created the basic structure for a Django project with settings and configurations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Creating a New Django App: polls&lt;/strong&gt;&lt;br&gt;
After setting up the project, I created a new app called polls, which would contain all the logic and views for my poll application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py startapp polls

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I added the new app to INSTALLED_APPS in mysite/settings.py:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSTALLED_APPS = [
    # other installed apps
    'polls',
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Defining the Models&lt;/strong&gt;&lt;br&gt;
I started by defining two models: Question and Choice. A Question has a question text and a publication date, while a Choice has a reference to a Question and stores text along with a vote count.&lt;/p&gt;

&lt;p&gt;Here’s the models.py file in the polls app:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# models.py
import datetime
from django.db import models
from django.contrib import admin
from django.utils import timezone

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

    def __str__(self):
        return self.question_text

    @admin.display(
        boolean=True,
        ordering='pub_date',
        description='Published recently?',
    )
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) &amp;lt;= self.pub_date &amp;lt;= now

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

    def __str__(self):
        return self.choice_text

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Creating the Database and Running Migrations&lt;/strong&gt;&lt;br&gt;
Next, I created the database and applied migrations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py migrate

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I then created migration files for the polls app:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py makemigrations polls
python manage.py migrate

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Writing Views for the Poll App&lt;/strong&gt;&lt;br&gt;
I wrote several views to handle displaying a list of questions, showing question details, and showing voting results. These views are class-based, using Django’s built-in generic views.&lt;br&gt;
Creating Views for Polls&lt;br&gt;
I then created the views that control how data is displayed to the user. I used Django's generic views to keep things simple.&lt;/p&gt;

&lt;p&gt;Here’s the views.py file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Question, Choice

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """Exclude questions that aren't published yet."""
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def vote(request, question_id):
    return HttpResponse(f"You're voting on question {question_id}.")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;IndexView: Displays a list of the latest questions.&lt;/li&gt;
&lt;li&gt;DetailView: Shows the details of a specific question and its choices.&lt;/li&gt;
&lt;li&gt;ResultsView: Displays the results of a poll after voting.
The vote() function handles the user's vote submission.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;7. Configuring URLs&lt;/strong&gt;&lt;br&gt;
I added URL patterns to the urls.py file in the polls app to link each view to a specific URL.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# urls.py
from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('&amp;lt;int:pk&amp;gt;/', views.DetailView.as_view(), name='detail'),
    path('&amp;lt;int:pk&amp;gt;/results/', views.ResultsView.as_view(), name='results'),
    path('&amp;lt;int:question_id&amp;gt;/vote/', views.vote, name='vote'),
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;8. Creating Templates for Views&lt;/strong&gt;&lt;br&gt;
Finally, I created HTML templates to display the questions and results. The templates are placed in the polls/templates/polls/ folder.&lt;/p&gt;

&lt;p&gt;index.html&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% if latest_question_list %}
    &amp;lt;ul&amp;gt;
        {% for question in latest_question_list %}
            &amp;lt;li&amp;gt;&amp;lt;a href="{% url 'polls:detail' question.id %}"&amp;gt;{{ question.question_text }}&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
        {% endfor %}
    &amp;lt;/ul&amp;gt;
{% else %}
    &amp;lt;p&amp;gt;No polls are available.&amp;lt;/p&amp;gt;
{% endif %}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;detail.html&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;form action="{% url 'polls:vote' question.id %}" method="post"&amp;gt;
    {% csrf_token %}
    &amp;lt;fieldset&amp;gt;
        &amp;lt;legend&amp;gt;&amp;lt;h1&amp;gt;{{ question.question_text }}&amp;lt;/h1&amp;gt;&amp;lt;/legend&amp;gt;
        {% if error_message %}&amp;lt;p&amp;gt;&amp;lt;strong&amp;gt;{{ error_message }}&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;{% endif %}
        {% for choice in question.choice_set.all %}
            &amp;lt;input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"&amp;gt;
            &amp;lt;label for="choice{{ forloop.counter }}"&amp;gt;{{ choice.choice_text }}&amp;lt;/label&amp;gt;&amp;lt;br&amp;gt;
        {% endfor %}
    &amp;lt;/fieldset&amp;gt;
    &amp;lt;input type="submit" value="Vote"&amp;gt;
&amp;lt;/form&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;result.html&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h1&amp;gt;{{ question.question_text }}&amp;lt;/h1&amp;gt;
&amp;lt;ul&amp;gt;
    {% for choice in question.choice_set.all %}
        &amp;lt;li&amp;gt;{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}&amp;lt;/li&amp;gt;
    {% endfor %}
&amp;lt;/ul&amp;gt;
&amp;lt;a href="{% url 'polls:detail' question.id %}"&amp;gt;Vote again?&amp;lt;/

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Running the Application&lt;/strong&gt;&lt;br&gt;
To test the application, I ran the development server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py runserver

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Navigating to &lt;a href="http://127.0.0.1:8000/polls/" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/polls/&lt;/a&gt; displayed the list of polls, and I could view details, vote, and see results.&lt;/p&gt;

&lt;p&gt;Over the past two weeks, I learned how to set up Django, create a project, and build a fully functioning poll app. It was fascinating to see how everything connects in Django, from models to views to templates. This has been a great experience, and I’m excited to learn more about Django's powerful features!&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>webdev</category>
      <category>python</category>
      <category>productivity</category>
    </item>
  </channel>
</rss>
