<?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: Maskini Mnene</title>
    <description>The latest articles on DEV Community by Maskini Mnene (@maskini_mnene_e9ec6dfd18d).</description>
    <link>https://dev.to/maskini_mnene_e9ec6dfd18d</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%2F2081200%2F1c1cadd6-1a94-46f4-8857-eff4db530610.jpg</url>
      <title>DEV Community: Maskini Mnene</title>
      <link>https://dev.to/maskini_mnene_e9ec6dfd18d</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/maskini_mnene_e9ec6dfd18d"/>
    <language>en</language>
    <item>
      <title>Building a Simple Polling App in Django: Step-by-Step Guide</title>
      <dc:creator>Maskini Mnene</dc:creator>
      <pubDate>Mon, 16 Sep 2024 13:48:53 +0000</pubDate>
      <link>https://dev.to/swahilipotdevs/technical-synopsis-activities-finalised-during-the-last-two-weeks-4738</link>
      <guid>https://dev.to/swahilipotdevs/technical-synopsis-activities-finalised-during-the-last-two-weeks-4738</guid>
      <description>&lt;p&gt;We will go through setting up a Django project from scratch to create a simple polling application. This guide will cover everything from installing Python and Django to configuring your app with models, views, and templates. Along the way, we will build a feature that lets users vote in a poll, and we will explore key concepts like generic views, models, and URL routing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Installing Python and Setting Up a Virtual Environment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before you start with Django, make sure you have Python installed on your machine. If you don’t have it installed, you can download Python from python.org.&lt;/p&gt;

&lt;p&gt;To keep your project’s dependencies isolated, it’s best to use 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 venv

# Activate the virtual environment
venv\Scripts\activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Installing Django and Starting a Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With your virtual environment activated, install 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;Now, create a new Django project called 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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command creates a mysite directory that contains your project files.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Creating the Polls App&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Django follows a modular approach, and every feature in Django is usually built inside an "app". We will create an app called polls.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;Next, register the polls app in mysite/settings.py by adding it to the INSTALLED_APPS list:&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 apps...
    'polls',
]

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Defining Models for Questions and Choices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In polls/models.py, we will define two models: Question and Choice. Each Question will have several Choices that users can vote on.&lt;br&gt;
&lt;/p&gt;

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

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

    def __str__(self):
        return self.question_text

    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;Step 5: Creating and Migrating the Database&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We will be using SQLite for our database, which is the default for Django. The configuration can be found in mysite/settings.py under the DATABASES section:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

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

&lt;/div&gt;



&lt;p&gt;After setting up the models, you need to generate the migrations and apply them to create the database schema:&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
python manage.py migrate

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 6: Creating Views for Polls&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We will use Django’s generic views to simplify the process of creating list and detail views. In polls/views.py, define views for listing questions, showing details of a question, and displaying results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.db.models import F
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 Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

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

    def get_queryset(self):
        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):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes = F('votes') + 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 7: Mapping URLs to Views&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In polls/urls.py, define the URL patterns for our app, which will map the URL paths to the views we just created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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;Then, include the polls/urls.py in the main mysite/urls.py:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 8: Creating Templates&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In polls/templates/polls/, create the HTML templates. First, index.html will display the list of questions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% load static %}

&amp;lt;link rel="stylesheet" href="{% static 'polls/style.css' %}"&amp;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;Next, the detail.html template will display the voting form for a question:&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;form action="{% url 'polls:vote' question.id %}" method="post"&amp;gt;
    {% csrf_token %}
    {% 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;input type="submit" value="Vote"&amp;gt;
&amp;lt;/form&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 %}

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

&lt;/div&gt;



&lt;p&gt;Lastly, results.html will display the voting results:&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;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 9: Running the Development Server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that everything is set up, you can start the Django 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;



</description>
    </item>
  </channel>
</rss>
