[
  {
    "path": ".gitignore",
    "content": "*.log\n*.pot\n*.pyc\n__pycache__/\nlocal_settings.py\ndb.sqlite3\nmedia\nvenv\n.vscode"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2019 Mahmudul Alam\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Django-Poll-App\n\nDjango poll app is a full featured polling app. You have to register in this app to show the polls and to vote. If you already voted you can not vote again. Only the owner of a poll can add poll , edit poll, update poll, delete poll , add choice, update choice, delete choice and end a poll. If a poll is ended it can not be voted. Ended poll only shows user the final result of the poll. There is a search option for polls. Also user can filter polls by name, publish date, and by number of voted. Pagination will work even after applying filter.\n\n<h1>Getting Started</h1>\n<p>These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.</p>\n\n<h2>Prerequisites</h2>\n<code>python== 3.5 or up and django==2.0 or up</code>\n\n<h2>Installing</h2>\n<pre>open terminal and type</pre>\n<code>git clone https://github.com/devmahmud/Django-poll-app.git</code><br><br>\n\n<h4>or simply download using the url below</h4>\n<code>https://github.com/devmahmud/Django-poll-app.git</code><br>\n\n<h2>To migrate the database open terminal in project directory and type</h2>\n<code>python manage.py makemigrations</code><br>\n<code>python manage.py migrate</code>\n\n<h2>To use admin panel you need to create superuser using this command </h2>\n<code>python manage.py createsuperuser</code>\n\n<h2>To Create some dummy text data for your app follow the step below:</h2>\n<code>pip install faker</code>\n<code>python manage.py shell</code>\n<code>import seeder</code>\n<code>seeder.seed_all(30)</code>\n<p>Here 30 is a number of entry. You can use it as your own</p>\n\n<h2> To run the program in local server use the following command </h2>\n<code>python manage.py runserver</code>\n\n<p>Then go to http://127.0.0.1:8000 in your browser</p>\n\n<h2>Project snapshot</h2>\n<h3>Home page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409444-0e40a600-1b8c-11e9-9ab0-27d759db8973.jpg\" width=\"100%\"</img> \n</div>\n\n<h3>Login Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409509-36c8a000-1b8c-11e9-845a-65b49262aa53.png\" width=\"100%\"</img> \n</div>\n\n<h3>Registration Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409562-5cee4000-1b8c-11e9-82f6-1aa2df159528.png\" width=\"100%\"</img> \n</div>\n\n<h3>Poll List Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409728-d423d400-1b8c-11e9-8903-4c08ba64512e.png\" width=\"100%\"</img> \n</div>\n\n<h3>Poll Add Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409796-fe759180-1b8c-11e9-941b-c1202956cca4.png\" width=\"100%\"</img> \n</div>\n\n<h3>Polling page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409843-1e0cba00-1b8d-11e9-9109-cceb79a6a623.png\" width=\"100%\"</img> \n</div>\n\n<h3>Poll Result Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51409932-60ce9200-1b8d-11e9-9c83-c59ba498ca8b.png\" width=\"100%\"</img> \n</div>\n\n<h3>Poll Edit Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51410008-92dff400-1b8d-11e9-8172-c228e4b60e28.png\" width=\"100%\"</img> \n</div>\n\n<h3>Choice Update Delete Page</h3>\n<div align=\"center\">\n    <img src=\"https://user-images.githubusercontent.com/19981097/51410442-dc7d0e80-1b8e-11e9-8f8e-18e6d7bb70fb.png\" width=\"100%\"</img> \n</div>\n\n<h2>Author</h2>\n<blockquote>\n  Mahmudul alam<br>\n  Email: expelmahmud@gmail.com\n</blockquote>\n\n<div align=\"center\">\n    <h3>========Thank You !!!=========</h3>\n</div>\n"
  },
  {
    "path": "accounts/__init__.py",
    "content": ""
  },
  {
    "path": "accounts/admin.py",
    "content": "from django.contrib import admin\n\n# Register your models here.\n"
  },
  {
    "path": "accounts/apps.py",
    "content": "from django.apps import AppConfig\n\n\nclass AccountsConfig(AppConfig):\n    name = 'accounts'\n"
  },
  {
    "path": "accounts/forms.py",
    "content": "from django import forms\nfrom django.contrib.auth.models import User\n\n\nclass UserRegistrationForm(forms.Form):\n    username = forms.CharField(label='Username', max_length=100, min_length=5,\n                               widget=forms.TextInput(attrs={'class': 'form-control'}))\n    email = forms.EmailField(label='Email', max_length=35, min_length=5,\n                             widget=forms.EmailInput(attrs={'class': 'form-control'}))\n    password1 = forms.CharField(label='Password', max_length=50, min_length=5,\n                                widget=forms.PasswordInput(attrs={'class': 'form-control'}))\n    password2 = forms.CharField(label='Confirm Password',\n                                max_length=50, min_length=5,\n                                widget=forms.PasswordInput(attrs={'class': 'form-control'}))\n"
  },
  {
    "path": "accounts/migrations/__init__.py",
    "content": ""
  },
  {
    "path": "accounts/models.py",
    "content": "from django.db import models\n\n# Create your models here.\n"
  },
  {
    "path": "accounts/templates/accounts/login.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n    <div class=\"vh-100 d-flex justify-content-center align-items-center p-5\" id=\"login-content\">\n        <div class=\"col-md-5 p-5 shadow-sm border rounded-5 border-primary bg-white\">\n            <h2 class=\"text-center mb-4 text-primary\">Login</h2>\n            {% if messages %}\n                <div class=\"messages\">\n                    {% for message in messages %}\n                        <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n                            <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                                <span aria-hidden=\"true\">&times;</span>\n                            </button>\n                        </div>\n                    {% endfor %}\n                </div>\n            {% endif %}\n            <form action=\"\" method=\"post\">\n                {% csrf_token %}\n                <div class=\"mb-3\">\n                    <label for=\"username\" class=\"form-label\">Username</label>\n                    <input type=\"text\" class=\"form-control border border-primary\" id=\"username\"\n                           aria-describedby=\"username\" name=\"username\" placeholder=\"Enter Username\" required>\n                </div>\n                <div class=\"mb-3\">\n                    <label for=\"password\" class=\"form-label\">Password</label>\n                    <input type=\"password\" class=\"form-control border border-primary\" name=\"password\"\n                           placeholder=\"Password\" required>\n                </div>\n                <div class=\"d-grid\">\n                    <button class=\"btn btn-primary\" type=\"submit\">Login</button>\n                </div>\n            </form>\n            <div class=\"mt-3\">\n                <p class=\"mb-0  text-center\">Don't have an account? <a href=\"{% url 'accounts:register' %}\"\n                                                                       class=\"text-primary fw-bold\">Sign\n                    Up</a></p>\n            </div>\n        </div>\n    </div>\n{% endblock %}"
  },
  {
    "path": "accounts/templates/accounts/register.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n<div class=\"container\">\n    <div class=\"row center\">\n        <div class=\"col-md-5 mx-auto p-5 shadow-sm border rounded border-primary\">\n            <p>Already have an account? <a href=\"{% url 'accounts:login' %}\">Login Here</a></p>\n            {% if messages %}\n            <div class=\"messages\">\n                {% for message in messages %}\n                <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n                    <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                        <span aria-hidden=\"true\">&times;</span>\n                    </button>\n                </div>\n                {% endfor %}\n            </div>\n            {% endif %}\n            <form action=\"\" method=\"POST\">\n                {% csrf_token %}\n                {{ form.as_p }}\n                <button type=\"submit\" class=\"btn btn-primary\">Sign Up</button>\n            </form>\n        </div>\n    </div>\n</div>\n{% endblock %}"
  },
  {
    "path": "accounts/tests.py",
    "content": "from django.test import TestCase\n\n# Create your tests here.\n"
  },
  {
    "path": "accounts/urls.py",
    "content": "from django.urls import path\nfrom . import views\n\napp_name = \"accounts\"\n\nurlpatterns=[\n    path('login/', views.login_user, name='login'),\n    path('logout/', views.logout_user, name='logout'),\n    path('register/', views.create_user, name='register'),\n]"
  },
  {
    "path": "accounts/views.py",
    "content": "from django.contrib.auth import authenticate, login, logout\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom .forms import UserRegistrationForm\nfrom django.contrib import messages\nfrom django.http import HttpResponse\n\n\ndef login_user(request):\n    if request.method == 'POST':\n        username = request.POST.get('username')\n        password = request.POST.get('password')\n        user = authenticate(username=username, password=password)\n\n        if user is not None:\n            login(request, user)\n            redirect_url = request.GET.get('next', 'home')\n            return redirect(redirect_url)\n        else:\n            messages.error(request, \"Username Or Password is incorrect!\",\n                           extra_tags='alert alert-warning alert-dismissible fade show')\n\n    return render(request, 'accounts/login.html')\n\n\ndef logout_user(request):\n    logout(request)\n    return redirect('home')\n\n\ndef create_user(request):\n    if request.method == 'POST':\n        check1 = False\n        check2 = False\n        check3 = False\n        form = UserRegistrationForm(request.POST)\n        if form.is_valid():\n            username = form.cleaned_data['username']\n            password1 = form.cleaned_data['password1']\n            password2 = form.cleaned_data['password2']\n            email = form.cleaned_data['email']\n\n            if password1 != password2:\n                check1 = True\n                messages.error(request, 'Password did not match!',\n                               extra_tags='alert alert-warning alert-dismissible fade show')\n            if User.objects.filter(username=username).exists():\n                check2 = True\n                messages.error(request, 'Username already exists!',\n                               extra_tags='alert alert-warning alert-dismissible fade show')\n            if User.objects.filter(email=email).exists():\n                check3 = True\n                messages.error(request, 'Email already registered!',\n                               extra_tags='alert alert-warning alert-dismissible fade show')\n\n            if check1 or check2 or check3:\n                messages.error(\n                    request, \"Registration Failed!\", extra_tags='alert alert-warning alert-dismissible fade show')\n                return redirect('accounts:register')\n            else:\n                user = User.objects.create_user(\n                    username=username, password=password1, email=email)\n                messages.success(\n                    request, f'Thanks for registering {user.username}.', extra_tags='alert alert-success alert-dismissible fade show')\n                return redirect('accounts:login')\n    else:\n        form = UserRegistrationForm()\n    return render(request, 'accounts/register.html', {'form': form})\n"
  },
  {
    "path": "manage.py",
    "content": "#!/usr/bin/env python\nimport os\nimport sys\n\nif __name__ == '__main__':\n    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pollme.settings')\n    try:\n        from django.core.management import execute_from_command_line\n    except ImportError as exc:\n        raise ImportError(\n            \"Couldn't import Django. Are you sure it's installed and \"\n            \"available on your PYTHONPATH environment variable? Did you \"\n            \"forget to activate a virtual environment?\"\n        ) from exc\n    execute_from_command_line(sys.argv)\n"
  },
  {
    "path": "pollme/__init__.py",
    "content": ""
  },
  {
    "path": "pollme/settings.py",
    "content": "\"\"\"\nDjango settings for pollme project.\n\nGenerated by 'django-admin startproject' using Django 2.1.5.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.1/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.1/ref/settings/\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"x*za6xf&_80ofdpae!yzq61g9ffikkx9$*iygbl$j7rr4wlf8t\"\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n    \"django.contrib.admin\",\n    \"django.contrib.auth\",\n    \"django.contrib.contenttypes\",\n    \"django.contrib.sessions\",\n    \"django.contrib.messages\",\n    \"django.contrib.staticfiles\",\n    \"polls.apps.PollsConfig\",\n    \"accounts.apps.AccountsConfig\",\n]\n\nMIDDLEWARE = [\n    \"django.middleware.security.SecurityMiddleware\",\n    \"django.contrib.sessions.middleware.SessionMiddleware\",\n    \"django.middleware.common.CommonMiddleware\",\n    \"django.middleware.csrf.CsrfViewMiddleware\",\n    \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n    \"django.contrib.messages.middleware.MessageMiddleware\",\n    \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n]\n\nROOT_URLCONF = \"pollme.urls\"\n\nTEMPLATES = [\n    {\n        \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n        \"DIRS\": [os.path.join(BASE_DIR, \"templates\")],\n        \"APP_DIRS\": True,\n        \"OPTIONS\": {\n            \"context_processors\": [\n                \"django.template.context_processors.debug\",\n                \"django.template.context_processors.request\",\n                \"django.contrib.auth.context_processors.auth\",\n                \"django.contrib.messages.context_processors.messages\",\n            ],\n        },\n    },\n]\n\nWSGI_APPLICATION = \"pollme.wsgi.application\"\n\n\n# Database\n# https://docs.djangoproject.com/en/2.1/ref/settings/#databases\n\nDATABASES = {\n    \"default\": {\n        \"ENGINE\": \"django.db.backends.sqlite3\",\n        \"NAME\": os.path.join(BASE_DIR, \"db.sqlite3\"),\n    }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.1/topics/i18n/\n\nLANGUAGE_CODE = \"en-us\"\n\nTIME_ZONE = \"Asia/Dhaka\"\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.1/howto/static-files/\n\nSTATIC_URL = \"/static/\"\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")]\n\nDEFAULT_AUTO_FIELD = \"django.db.models.AutoField\"\n"
  },
  {
    "path": "pollme/urls.py",
    "content": "\"\"\"pollme URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n    https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n    1. Add an import:  from my_app import views\n    2. Add a URL to urlpatterns:  path('', views.home, name='home')\nClass-based views\n    1. Add an import:  from other_app.views import Home\n    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')\nIncluding another URLconf\n    1. Import the include() function: from django.urls import include, path\n    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n    path('', views.home, name='home'),\n    path('admin/', admin.site.urls),\n    path('accounts/', include('accounts.urls', namespace=\"accounts\")),\n    path('polls/', include('polls.urls', namespace=\"polls\")),\n]\n"
  },
  {
    "path": "pollme/views.py",
    "content": "from django.shortcuts import render\n\n\ndef home(request):\n    return render(request,'home.html')"
  },
  {
    "path": "pollme/wsgi.py",
    "content": "\"\"\"\nWSGI config for pollme project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/\n\"\"\"\n\nimport os\n\nfrom django.core.wsgi import get_wsgi_application\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pollme.settings')\n\napplication = get_wsgi_application()\n"
  },
  {
    "path": "polls/__init__.py",
    "content": ""
  },
  {
    "path": "polls/admin.py",
    "content": "from django.contrib import admin\nfrom .models import Poll, Choice, Vote\n\n\nclass ChoiceInline(admin.TabularInline):  # or admin.StackedInline for a different layout\n    model = Choice\n    extra = 1\n\n@admin.register(Poll)\nclass PollAdmin(admin.ModelAdmin):\n    list_display = [\"text\", \"owner\", \"pub_date\", \"active\", \"created_at\"]\n    search_fields = [\"text\", \"owner__username\"]\n    list_filter = [\"active\", 'created_at', 'pub_date']\n    date_hierarchy = \"pub_date\"\n    inlines = [ChoiceInline]\n\n\n@admin.register(Choice)\nclass ChoiceAdmin(admin.ModelAdmin):\n    list_display = [\"choice_text\", \"poll\", 'created_at', 'updated_at']\n    search_fields = [\"choice_text\", \"poll__text\"]\n    autocomplete_fields = [\"poll\"]\n\n\n@admin.register(Vote)\nclass VoteAdmin(admin.ModelAdmin):\n    list_display = [\"choice\", \"poll\", \"user\", 'created_at']\n    search_fields = [\"choice__choice_text\", \"poll__text\", \"user__username\"]\n    autocomplete_fields = [\"choice\", \"poll\", \"user\"]\n"
  },
  {
    "path": "polls/apps.py",
    "content": "from django.apps import AppConfig\n\n\nclass PollsConfig(AppConfig):\n    name = 'polls'\n"
  },
  {
    "path": "polls/forms.py",
    "content": "from django import forms\nfrom .models import Poll, Choice\n\n\nclass PollAddForm(forms.ModelForm):\n\n    choice1 = forms.CharField(label='Choice 1', max_length=100, min_length=1,\n                              widget=forms.TextInput(attrs={'class': 'form-control'}))\n    choice2 = forms.CharField(label='Choice 2', max_length=100, min_length=1,\n                              widget=forms.TextInput(attrs={'class': 'form-control'}))\n\n    class Meta:\n        model = Poll\n        fields = ['text', 'choice1', 'choice2']\n        widgets = {\n            'text': forms.Textarea(attrs={'class': 'form-control', 'rows': 5, 'cols': 20}),\n        }\n\n\nclass EditPollForm(forms.ModelForm):\n    class Meta:\n        model = Poll\n        fields = ['text', ]\n        widgets = {\n            'text': forms.Textarea(attrs={'class': 'form-control', 'rows': 5, 'cols': 20}),\n        }\n\n\nclass ChoiceAddForm(forms.ModelForm):\n    class Meta:\n        model = Choice\n        fields = ['choice_text', ]\n        widgets = {\n            'choice_text': forms.TextInput(attrs={'class': 'form-control', })\n        }\n"
  },
  {
    "path": "polls/migrations/0001_initial.py",
    "content": "# Generated by Django 3.1.5 on 2021-01-29 16:38\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n    initial = True\n\n    dependencies = [\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='Choice',\n            fields=[\n                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n                ('choice_text', models.CharField(max_length=255)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Poll',\n            fields=[\n                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n                ('text', models.TextField()),\n                ('pub_date', models.DateTimeField(default=django.utils.timezone.now)),\n                ('active', models.BooleanField(default=True)),\n                ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Vote',\n            fields=[\n                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n                ('choice', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.choice')),\n                ('poll', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.poll')),\n                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n        migrations.AddField(\n            model_name='choice',\n            name='poll',\n            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.poll'),\n        ),\n    ]\n"
  },
  {
    "path": "polls/migrations/0002_auto_20231018_1318.py",
    "content": "# Generated by Django 3.1.14 on 2023-10-18 07:18\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('polls', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='choice',\n            name='created_at',\n            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='choice',\n            name='updated_at',\n            field=models.DateTimeField(auto_now=True),\n        ),\n        migrations.AddField(\n            model_name='poll',\n            name='created_at',\n            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='vote',\n            name='created_at',\n            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),\n            preserve_default=False,\n        ),\n        migrations.AddField(\n            model_name='vote',\n            name='updated_at',\n            field=models.DateTimeField(auto_now=True),\n        ),\n    ]\n"
  },
  {
    "path": "polls/migrations/__init__.py",
    "content": ""
  },
  {
    "path": "polls/models.py",
    "content": "from django.contrib.auth.models import User\nfrom django.db import models\nfrom django.utils import timezone\nimport secrets\n\n\nclass Poll(models.Model):\n    owner = models.ForeignKey(User, on_delete=models.CASCADE)\n    text = models.TextField()\n    pub_date = models.DateTimeField(default=timezone.now)\n    active = models.BooleanField(default=True)\n    created_at = models.DateTimeField(auto_now_add=True)\n\n    def user_can_vote(self, user):\n        \"\"\" \n        Return False if user already voted\n        \"\"\"\n        user_votes = user.vote_set.all()\n        qs = user_votes.filter(poll=self)\n        if qs.exists():\n            return False\n        return True\n\n    @property\n    def get_vote_count(self):\n        return self.vote_set.count()\n\n    def get_result_dict(self):\n        res = []\n        for choice in self.choice_set.all():\n            d = {}\n            alert_class = ['primary', 'secondary', 'success',\n                           'danger', 'dark', 'warning', 'info']\n\n            d['alert_class'] = secrets.choice(alert_class)\n            d['text'] = choice.choice_text\n            d['num_votes'] = choice.get_vote_count\n            if not self.get_vote_count:\n                d['percentage'] = 0\n            else:\n                d['percentage'] = (choice.get_vote_count /\n                                   self.get_vote_count)*100\n\n            res.append(d)\n        return res\n\n    def __str__(self):\n        return self.text\n\n\nclass Choice(models.Model):\n    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)\n    choice_text = models.CharField(max_length=255)\n    created_at = models.DateTimeField(auto_now_add=True)\n    updated_at = models.DateTimeField(auto_now=True)\n\n    @property\n    def get_vote_count(self):\n        return self.vote_set.count()\n\n    def __str__(self):\n        return f\"{self.poll.text[:25]} - {self.choice_text[:25]}\"\n\n\nclass Vote(models.Model):\n    user = models.ForeignKey(User, on_delete=models.CASCADE)\n    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)\n    choice = models.ForeignKey(Choice, on_delete=models.CASCADE)\n    created_at = models.DateTimeField(auto_now_add=True)\n    updated_at = models.DateTimeField(auto_now=True)\n\n    def __str__(self):\n        return f'{self.poll.text[:15]} - {self.choice.choice_text[:15]} - {self.user.username}'\n"
  },
  {
    "path": "polls/templates/polls/add_choice.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n<div class=\"container\">\n    <div class=\"row center\">\n        <div class=\"col-md-6 offset-md-3\">\n            {% if edit_choice %}\n            <h2>Update choice</h2>\n            {% else %}\n            <h2>Add new choice</h2>\n            {% endif %}\n            {% if messages %}\n            <ul class=\"messages\">\n                {% for message in messages %}\n                <li {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}</li>\n                {% endfor %}\n            </ul>\n            {% endif %}\n            <form action=\"\" method=\"POST\">\n                {% csrf_token %}\n                {% for field in form %}\n                <div class=\"form-group\">\n                    {{ field.errors }}\n                    {{ field.label_tag }}\n                    {{ field }}\n                </div>\n                {% endfor %}\n                {% if edit_choice %}\n                <button type=\"submit\" class=\"btn btn-primary\">Update</button>\n                <a class=\"btn btn-danger\" href=\"{% url 'polls:choice_delete' choice.id %}\" role=\"button\" onclick=\"return confirm('Are you sure you want to delete this?')\">Delete</a>\n                {% else %}\n                <button type=\"submit\" class=\"btn btn-primary\">Add</button>\n                {% endif %}\n            </form>\n        </div>\n    </div>\n</div>\n{% endblock %}"
  },
  {
    "path": "polls/templates/polls/add_poll.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n<div class=\"container\">\n    <div class=\"row center\">\n        <div class=\"col-md-6 offset-md-3\">\n            <h2>Create new poll</h2>\n            {% if messages %}\n            <ul class=\"messages\">\n                {% for message in messages %}\n                <li {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}</li>\n                {% endfor %}\n            </ul>\n            {% endif %}\n            <form action=\"\" method=\"POST\">\n                {% csrf_token %}\n                {% for field in form %}\n                <div class=\"form-group\">\n                    {{ field.errors }}\n                    {{ field.label_tag }}\n                    {{ field }}\n                </div>\n                {% endfor %}\n                <button type=\"submit\" class=\"btn btn-primary\">Add Poll</button>\n                <a class=\"btn btn-warning\" href=\"{% url 'polls:list' %}\" role=\"button\">Back</a>\n            </form>\n        </div>\n    </div>\n</div>\n{% endblock %}"
  },
  {
    "path": "polls/templates/polls/endpoll.html",
    "content": "{% extends 'base.html' %}\n\n\n{% block content %}\n<div class=\"container\">\n    {% if messages %}\n    <div class=\"messages\">\n        {% for message in messages %}\n        <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n            <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                <span aria-hidden=\"true\">&times;</span>\n            </button>\n        </div>\n        {% endfor %}\n    </div>\n    {% else %}\n    <div class=\"row\">\n        <div class=\"col-md-8 offset-sm-2\">\n            <h3 class=\"mt-3 mb-3 text-center\">Result for: {{ poll.text }}</h3>\n            <!-- progress bar -->\n    <div class=\"progress mt-3\">\n\n        {% for choice in poll.get_result_dict %}\n        <div class=\"progress-bar bg-{{ choice.alert_class }}\" role=\"progressbar\" style=\"width: {{ choice.percentage }}%;\" aria-valuenow=\"30\" aria-valuemin=\"0\"\n            aria-valuemax=\"100\"><b>{{ choice.text }}-{{ choice.percentage|floatformat }}%</b></div>\n        {% endfor %}\n\n    </div>\n            <ul class=\"list-group\">\n                {% for choice in poll.choice_set.all %}\n                <li class=\"list-group-item d-flex justify-content-between align-items-center\">\n                    {{ choice.choice_text }}\n                    <span class=\"badge badge-primary badge-pill\">{{ choice.get_vote_count }}</span>\n                </li>\n                {% endfor %}\n            </ul>\n            {% endif %}\n            <a class=\"btn btn-primary mt-3\" href=\"{% url 'polls:list' %}\" role=\"button\">Back To Polls</a>\n        </div>\n        \n    </div>\n</div>\n{% endblock content %}"
  },
  {
    "path": "polls/templates/polls/poll_detail.html",
    "content": "{% extends 'base.html' %}\n\n\n{% block content %}\n<div class=\"container\">\n    <h1>Polls details page</h1>\n    {% if messages %}\n    <div class=\"messages\">\n        {% for message in messages %}\n        <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n            <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                <span aria-hidden=\"true\">&times;</span>\n            </button>\n        </div>\n        {% endfor %}\n    </div>\n    {% endif %}\n    <hr>\n    <h2 class=\"mt-3 mb-3\">{{ poll }}</h2>\n    <form action=\"{% url 'polls:vote' poll.id %}\" method=\"POST\">\n        {% csrf_token %}\n        {% for choice in poll.choice_set.all %}\n        <input type=\"radio\" name=\"choice\" id=\"choice{{ forloop.counter }}\" value=\"{{ choice.id }}\">\n        <label for=\"choice{{ forloop.counter }}\">{{ choice.choice_text }}</label>\n        <br>\n        {% endfor %}\n        <input type=\"submit\" value=\"Vote\" class=\"btn btn-primary mt-3\">\n        <a class=\"btn btn-warning mt-3\" href=\"{% url 'polls:list' %}\" role=\"button\">Cancel</a>\n    </form>\n\n</div>\n\n{% endblock content %}"
  },
  {
    "path": "polls/templates/polls/poll_edit.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n<div class=\"container\">\n    <div class=\"row center\">\n        <div class=\"col-md-6 offset-md-3\">\n            <h2>Edit poll</h2>\n            {% if messages %}\n            {% if messages %}\n            <div class=\"messages\">\n                {% for message in messages %}\n                <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n                    <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                        <span aria-hidden=\"true\">&times;</span>\n                    </button>\n                </div>\n                {% endfor %}\n            </div>\n            {% endif %}\n            {% endif %}\n            <form action=\"\" method=\"POST\">\n                {% csrf_token %}\n                {% for field in form %}\n                <div class=\"form-group\">\n                    {{ field.errors }}\n                    {{ field.label_tag }}\n                    {{ field }}\n                </div>\n                {% endfor %}\n                <button type=\"submit\" class=\"btn btn-primary\">Update</button>\n                <a class=\"btn btn-danger\" href=\"{% url 'polls:delete_poll' poll.id %}\" role=\"button\" onclick=\"return confirm('Are you sure?')\">Delete</a>\n                <a class=\"btn btn-warning\" href=\"{% url 'polls:add_choice' poll.id %}\" role=\"button\">Add Choice</a>\n            </form>\n\n            <div class=\"choices\">\n                <h2 class=\"text-center mt-3\">Choices</h2>\n                <hr>\n                <ul class=\"list-group\">\n                    {% for choice in poll.choice_set.all %}\n                    <li class=\"list-group-item\"><a href=\"{% url 'polls:choice_edit' choice.id %}\"><i class=\"fas fa-pencil-alt\"></i></a>&nbsp\n                        {{ choice.choice_text }}</li>\n                    {% endfor %}\n                </ul>\n            </div>\n\n        </div>\n    </div>\n</div>\n{% endblock %}"
  },
  {
    "path": "polls/templates/polls/poll_result.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n<div class=\"container\">\n    {% if messages %}\n    <div class=\"messages\">\n        {% for message in messages %}\n        <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n            <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                <span aria-hidden=\"true\">&times;</span>\n            </button>\n        </div>\n        {% endfor %}\n    </div>\n    {% else %}\n    <div class=\"row\">\n        <div class=\"col-md-8 offset-sm-2\">\n            {% if poll.active %}\n            <h3 class=\"mt-3 mb-3 text-center\">Result for: {{ poll.text }}</h3>\n            {% else %}\n            <h3 class=\"mt-3 mb-3 text-center\">\"{{ poll.text }}\" Has Ended Polling!</h3>\n            {% endif %}\n            <h3 class=\"mb-2 text-center\">Total: {{ poll.get_vote_count }} votes</h3>\n            <!-- progress bar -->\n            <div class=\"progress mt-3 mb-2\">\n                {% for choice in poll.get_result_dict %}\n                <div class=\"progress-bar bg-{{ choice.alert_class }}\" role=\"progressbar\" style=\"width: {{ choice.percentage }}%;\"\n                    aria-valuenow=\"30\" aria-valuemin=\"0\" aria-valuemax=\"100\"><b>\n                        {{choice.text|truncatewords:2}}-{{choice.percentage|floatformat}}%</b>\n                </div>\n                {% endfor %}\n\n            </div>\n            <ul class=\"list-group\">\n                {% for choice in poll.choice_set.all %}\n                <li class=\"list-group-item d-flex justify-content-between align-items-center\">\n                    {{ choice.choice_text }}\n                    <span class=\"badge badge-primary badge-pill\">{{ choice.get_vote_count }}</span>\n                </li>\n                {% endfor %}\n            </ul>\n            {% endif %}\n            <a class=\"btn btn-primary mt-3\" href=\"{% url 'polls:list' %}\" role=\"button\">Back To Polls</a>\n        </div>\n\n    </div>\n</div>\n{% endblock content %}"
  },
  {
    "path": "polls/templates/polls/polls_list.html",
    "content": "{% extends 'base.html' %}\n\n{% block content %}\n<div class=\"container\">\n    <div class=\"row\">\n        <div class=\"col-md-8 offset-sm-2\">\n            <h1 class=\"text-center mb-5\">Welcome to polls List!</h1>\n            {% if messages %}\n            <div class=\"messages\">\n                {% for message in messages %}\n                <div {% if message.tags %} class=\"{{ message.tags }}\" {% endif %}>{{ message }}\n                    <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n                        <span aria-hidden=\"true\">&times;</span>\n                    </button>\n                </div>\n                {% endfor %}\n            </div>\n            {% endif %}\n\n            <a class=\"btn btn-{% if 'name' in request.GET %}warning{% else %}primary{% endif %} mb-3\" href=\"?name=True\"\n                role=\"button\"><i class=\"fas fa-sort-alpha-down\"></i>\n                Name</a>\n            <a class=\"btn btn-{% if 'date' in request.GET %}warning{% else %}primary{% endif %} mb-3\" href=\"?date=True\"\n                role=\"button\"><i class=\"far fa-clock\"></i> Date</a>\n            <a class=\"btn btn-{% if 'vote' in request.GET %}warning{% else %}primary{% endif %} mb-3\" href=\"?vote=True\"\n                role=\"button\"><i class=\"fas fa-poll\"></i> Vote</a>\n\n            <a class=\"btn btn-primary mb-3 float-right\" href=\"{% url 'polls:add' %}\" role=\"button\">Add <i class=\"fas fa-plus\"></i></a>\n\n            <form class=\"form-inline\">\n                <div class=\"form-group mr-sm-2 mb-2\">\n                    <input type=\"search\" class=\"form-control\" name=\"search\" placeholder=\"Search\" value={{ search_term }}>\n                </div>\n                <button type=\"submit\" class=\"btn btn-primary mb-2\"><i class=\"fas fa-search\"></i></button>\n            </form>\n\n\n            <ul class=\"list-group\">\n                {% for poll in polls %}\n                <li class=\"list-group-item\"><a href=\"{% url 'polls:detail' poll.id %}\">{{ poll.text|truncatewords:5 }}\n                        {% if not poll.active%}\n                        <i class=\"fas fa-check-circle ml-2\"></i>\n                        {% endif %}\n                    </a>\n                    {% if request.user == poll.owner %}\n                    {% if poll.active %}\n                    <a href=\"{% url 'polls:end_poll' poll.id %}\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"End Poll\"\n                        onclick=\"return confirm('Are you sure ?')\"><i class=\"fas fa-step-forward float-right btn btn-danger btn-sm\"></i></a>\n                    {% endif %}\n                    <a href=\"{% url 'polls:edit' poll.id %}\" class=\"mr-3\" data-toggle=\"tooltip\" data-placement=\"top\"\n                        title=\"Edit Poll\"><i class=\"fas fa-pencil-alt float-right btn btn-primary btn-sm mr-1\"></i></a>\n                    {% endif %}\n                </li>\n\n                {% endfor %}\n            </ul>\n            {% if polls.paginator.num_pages > 1 %}\n            <nav class=\"mt-3\">\n                <ul class=\"pagination\">\n                    {% if polls.has_previous %}\n                    <li class=\"page-item\"><a class=\"page-link\" href=\"?page=1&{{ params }}\">First</a></li>\n                    <li class=\"page-item\"><a class=\"page-link\" href=\"?page={{ polls.previous_page_number }}&{{ params }}\">Previous</a></li>\n                    {% endif %}\n\n                    <li class=\"page-item active\"><a class=\"page-link\" href=\"\">{{ polls.number }}</a></li>\n\n                    {% if polls.has_next %}\n                    <li class=\"page-item\"><a class=\"page-link\" href=\"?page={{ polls.next_page_number }}&{{ params }}\">Next</a></li>\n                    <li class=\"page-item\"><a class=\"page-link\" href=\"?page={{ polls.paginator.num_pages }}&{{ params }}\">Last</a></li>\n                    {% endif %}\n                </ul>\n            </nav>\n            {% endif %}\n        </div>\n    </div>\n</div>\n\n{% endblock content %}"
  },
  {
    "path": "polls/tests.py",
    "content": "from django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom .models import Poll, Vote\n\n\nclass PollModelTest(TestCase):\n    def test_user_can_vote(self):\n        user = User.objects.create_user('john')\n        poll = Poll.objects.create(owner=user)\n        self.assertTrue(poll.user_can_vote(user))\n\n        choice = poll.choice_set.create(choice_text='pizza')\n        Vote.objects.create(user=user, poll=poll, choice=choice)\n        self.assertFalse(poll.user_can_vote(user))\n\n\nclass PollViewTest(TestCase):\n    def test_home(self):\n        response = self.client.get('/')\n        self.assertEqual(response.status_code, 200)\n\n    def test_login(self):\n        User.objects.create_user(username='john', password='rambo')\n        response = self.client.post(\n            '/accounts/login/', {'username': 'john', 'password': 'rambo'}\n        )\n        self.assertRedirects(response, '/')\n\n    def test_register(self):\n        response = self.client.post(\n            '/accounts/register/',\n            {\n                'username': 'johny',\n                'password1': 'rambo',\n                'password2': 'rambo',\n                'email': 'johny.rambo@usarmy.gov',\n            },\n        )\n        self.assertRedirects(response, '/accounts/login/')\n        # assert that user got actually created in the backend\n        self.assertIsNotNone(authenticate(username='johny', password='rambo'))\n"
  },
  {
    "path": "polls/urls.py",
    "content": "from django.urls import path\nfrom . import views\n\napp_name = \"polls\"\n\nurlpatterns = [\n    path('list/', views.polls_list, name='list'),\n    path('list/user/', views.list_by_user, name='list_by_user'),\n    path('add/', views.polls_add, name='add'),\n    path('edit/<int:poll_id>/', views.polls_edit, name='edit'),\n    path('delete/<int:poll_id>/', views.polls_delete, name='delete_poll'),\n    path('end/<int:poll_id>/', views.end_poll, name='end_poll'),\n    path('edit/<int:poll_id>/choice/add/', views.add_choice, name='add_choice'),\n    path('edit/choice/<int:choice_id>/', views.choice_edit, name='choice_edit'),\n    path('delete/choice/<int:choice_id>/',\n         views.choice_delete, name='choice_delete'),\n    path('<int:poll_id>/', views.poll_detail, name='detail'),\n    path('<int:poll_id>/vote/', views.poll_vote, name='vote'),\n]\n"
  },
  {
    "path": "polls/views.py",
    "content": "from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.db.models import Count\nfrom django.contrib import messages\nfrom .models import Poll, Choice, Vote\nfrom .forms import PollAddForm, EditPollForm, ChoiceAddForm\nfrom django.http import HttpResponse\n\n\n@login_required()\ndef polls_list(request):\n    all_polls = Poll.objects.all()\n    search_term = ''\n    if 'name' in request.GET:\n        all_polls = all_polls.order_by('text')\n\n    if 'date' in request.GET:\n        all_polls = all_polls.order_by('pub_date')\n\n    if 'vote' in request.GET:\n        all_polls = all_polls.annotate(Count('vote')).order_by('vote__count')\n\n    if 'search' in request.GET:\n        search_term = request.GET['search']\n        all_polls = all_polls.filter(text__icontains=search_term)\n\n    paginator = Paginator(all_polls, 6)  # Show 6 contacts per page\n    page = request.GET.get('page')\n    polls = paginator.get_page(page)\n\n    get_dict_copy = request.GET.copy()\n    params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode()\n\n    context = {\n        'polls': polls,\n        'params': params,\n        'search_term': search_term,\n    }\n    return render(request, 'polls/polls_list.html', context)\n\n\n@login_required()\ndef list_by_user(request):\n    all_polls = Poll.objects.filter(owner=request.user)\n    paginator = Paginator(all_polls, 7)  # Show 7 contacts per page\n\n    page = request.GET.get('page')\n    polls = paginator.get_page(page)\n\n    context = {\n        'polls': polls,\n    }\n    return render(request, 'polls/polls_list.html', context)\n\n\n@login_required()\ndef polls_add(request):\n    if request.user.has_perm('polls.add_poll'):\n        if request.method == 'POST':\n            form = PollAddForm(request.POST)\n            if form.is_valid:\n                poll = form.save(commit=False)\n                poll.owner = request.user\n                poll.save()\n                Choice(\n                    poll=poll, choice_text=form.cleaned_data['choice1']).save()\n                Choice(\n                    poll=poll, choice_text=form.cleaned_data['choice2']).save()\n\n                messages.success(\n                    request, \"Poll & Choices added successfully.\", extra_tags='alert alert-success alert-dismissible fade show')\n\n                return redirect('polls:list')\n        else:\n            form = PollAddForm()\n        context = {\n            'form': form,\n        }\n        return render(request, 'polls/add_poll.html', context)\n    else:\n        return HttpResponse(\"Sorry but you don't have permission to do that!\")\n\n\n@login_required\ndef polls_edit(request, poll_id):\n    poll = get_object_or_404(Poll, pk=poll_id)\n    if request.user != poll.owner:\n        return redirect('home')\n\n    if request.method == 'POST':\n        form = EditPollForm(request.POST, instance=poll)\n        if form.is_valid:\n            form.save()\n            messages.success(request, \"Poll Updated successfully.\",\n                             extra_tags='alert alert-success alert-dismissible fade show')\n            return redirect(\"polls:list\")\n\n    else:\n        form = EditPollForm(instance=poll)\n\n    return render(request, \"polls/poll_edit.html\", {'form': form, 'poll': poll})\n\n\n@login_required\ndef polls_delete(request, poll_id):\n    poll = get_object_or_404(Poll, pk=poll_id)\n    if request.user != poll.owner:\n        return redirect('home')\n    poll.delete()\n    messages.success(request, \"Poll Deleted successfully.\",\n                     extra_tags='alert alert-success alert-dismissible fade show')\n    return redirect(\"polls:list\")\n\n\n@login_required\ndef add_choice(request, poll_id):\n    poll = get_object_or_404(Poll, pk=poll_id)\n    if request.user != poll.owner:\n        return redirect('home')\n\n    if request.method == 'POST':\n        form = ChoiceAddForm(request.POST)\n        if form.is_valid:\n            new_choice = form.save(commit=False)\n            new_choice.poll = poll\n            new_choice.save()\n            messages.success(\n                request, \"Choice added successfully.\", extra_tags='alert alert-success alert-dismissible fade show')\n            return redirect('polls:edit', poll.id)\n    else:\n        form = ChoiceAddForm()\n    context = {\n        'form': form,\n    }\n    return render(request, 'polls/add_choice.html', context)\n\n\n@login_required\ndef choice_edit(request, choice_id):\n    choice = get_object_or_404(Choice, pk=choice_id)\n    poll = get_object_or_404(Poll, pk=choice.poll.id)\n    if request.user != poll.owner:\n        return redirect('home')\n\n    if request.method == 'POST':\n        form = ChoiceAddForm(request.POST, instance=choice)\n        if form.is_valid:\n            new_choice = form.save(commit=False)\n            new_choice.poll = poll\n            new_choice.save()\n            messages.success(\n                request, \"Choice Updated successfully.\", extra_tags='alert alert-success alert-dismissible fade show')\n            return redirect('polls:edit', poll.id)\n    else:\n        form = ChoiceAddForm(instance=choice)\n    context = {\n        'form': form,\n        'edit_choice': True,\n        'choice': choice,\n    }\n    return render(request, 'polls/add_choice.html', context)\n\n\n@login_required\ndef choice_delete(request, choice_id):\n    choice = get_object_or_404(Choice, pk=choice_id)\n    poll = get_object_or_404(Poll, pk=choice.poll.id)\n    if request.user != poll.owner:\n        return redirect('home')\n    choice.delete()\n    messages.success(\n        request, \"Choice Deleted successfully.\", extra_tags='alert alert-success alert-dismissible fade show')\n    return redirect('polls:edit', poll.id)\n\n\ndef poll_detail(request, poll_id):\n    poll = get_object_or_404(Poll, id=poll_id)\n\n    if not poll.active:\n        return render(request, 'polls/poll_result.html', {'poll': poll})\n    loop_count = poll.choice_set.count()\n    context = {\n        'poll': poll,\n        'loop_time': range(0, loop_count),\n    }\n    return render(request, 'polls/poll_detail.html', context)\n\n\n@login_required\ndef poll_vote(request, poll_id):\n    poll = get_object_or_404(Poll, pk=poll_id)\n    choice_id = request.POST.get('choice')\n    if not poll.user_can_vote(request.user):\n        messages.error(\n            request, \"You already voted this poll!\", extra_tags='alert alert-warning alert-dismissible fade show')\n        return redirect(\"polls:list\")\n\n    if choice_id:\n        choice = Choice.objects.get(id=choice_id)\n        vote = Vote(user=request.user, poll=poll, choice=choice)\n        vote.save()\n        print(vote)\n        return render(request, 'polls/poll_result.html', {'poll': poll})\n    else:\n        messages.error(\n            request, \"No choice selected!\", extra_tags='alert alert-warning alert-dismissible fade show')\n        return redirect(\"polls:detail\", poll_id)\n    return render(request, 'polls/poll_result.html', {'poll': poll})\n\n\n@login_required\ndef end_poll(request, poll_id):\n    poll = get_object_or_404(Poll, pk=poll_id)\n    if request.user != poll.owner:\n        return redirect('home')\n\n    if poll.active is True:\n        poll.active = False\n        poll.save()\n        return render(request, 'polls/poll_result.html', {'poll': poll})\n    else:\n        return render(request, 'polls/poll_result.html', {'poll': poll})\n"
  },
  {
    "path": "requirements.txt",
    "content": "asgiref==3.3.1\n\"Django>=4.2,<4.3\"\npytz==2020.5\nsqlparse==0.4.4\n"
  },
  {
    "path": "seeder.py",
    "content": "from polls.models import Choice, Poll, Vote\nfrom django.contrib.auth.models import User\nimport datetime\nimport random\nimport time\nfrom faker import Faker\nfake = Faker()\n\n\ndef seed_users(num_entries=10, overwrite=False):\n    \"\"\"\n    Creates num_entries worth a new users\n    \"\"\"\n    if overwrite:\n        print(\"Overwriting Users\")\n        User.objects.all().delete()\n    count = 0\n    for _ in range(num_entries):\n        first_name = fake.first_name()\n        last_name = fake.last_name()\n        u = User.objects.create_user(\n            first_name=first_name,\n            last_name=last_name,\n            email=first_name + \".\" + last_name + \"@fakermail.com\",\n            username=first_name + last_name,\n            password=\"password\"\n        )\n        count += 1\n        percent_complete = count / num_entries * 100\n        print(\n            \"Adding {} new Users: {:.2f}%\".format(\n                num_entries, percent_complete),\n            end='\\r',\n            flush=True\n        )\n    print()\n\n\ndef seed_polls(num_entries=10, choice_min=2, choice_max=5, overwrite=False):\n    \"\"\"\n    Seeds num_entries poll with random users as owners\n    Each poll will be seeded with # choices from choice_min to choice_max\n    \"\"\"\n    if overwrite:\n        print('Overwriting polls')\n        Poll.objects.all().delete()\n    users = list(User.objects.all())\n    count = 0\n    for _ in range(num_entries):\n        p = Poll(\n            owner=random.choice(users),\n            text=fake.paragraph(),\n            pub_date=datetime.datetime.now()\n        )\n        p.save()\n        num_choices = random.randrange(choice_min, choice_max + 1)\n        for _ in range(num_choices):\n            c = Choice(\n                poll=p,\n                choice_text=fake.sentence()\n            ).save()\n        count += 1\n        percent_complete = count / num_entries * 100\n        print(\n            \"Adding {} new Polls: {:.2f}%\".format(\n                num_entries, percent_complete),\n            end='\\r',\n            flush=True\n        )\n    print()\n\n\ndef seed_votes():\n    \"\"\"\n    Creates a new vote on every poll for every user\n    Voted for choice is selected random.\n    Deletes all votes prior to adding new ones\n    \"\"\"\n    Vote.objects.all().delete()\n    users = User.objects.all()\n    polls = Poll.objects.all()\n    count = 0\n    number_of_new_votes = users.count() * polls.count()\n    for poll in polls:\n        choices = list(poll.choice_set.all())\n        for user in users:\n            v = Vote(\n                user=user,\n                poll=poll,\n                choice=random.choice(choices)\n            ).save()\n            count += 1\n            percent_complete = count / number_of_new_votes * 100\n            print(\n                \"Adding {} new votes: {:.2f}%\".format(\n                    number_of_new_votes, percent_complete),\n                end='\\r',\n                flush=True\n            )\n    print()\n\n\ndef seed_all(num_entries=10, overwrite=False):\n    \"\"\"\n    Runs all seeder functions. Passes value of overwrite to all\n    seeder function calls.\n    \"\"\"\n    start_time = time.time()\n    # run seeds\n    seed_users(num_entries=num_entries, overwrite=overwrite)\n    seed_polls(num_entries=num_entries, overwrite=overwrite)\n    seed_votes()\n    # get time\n    elapsed_time = time.time() - start_time\n    minutes = int(elapsed_time // 60)\n    seconds = int(elapsed_time % 60)\n    print(\"Script Execution took: {} minutes {} seconds\".format(minutes, seconds))\n"
  },
  {
    "path": "static/css/home_style.css",
    "content": "html, body {\n    height:100%;\n    padding: 0;\n    margin: 0;\n    color: white;\n  }\nhtml{\n    background-image: url('../img/background.jpg');\n    background-size: cover;\n}\nbody {\n    background: rgba(0, 0, 0, 0.466);\n}\n#home-content{\n    text-align: center;\n    padding-top: 20%;\n}"
  },
  {
    "path": "templates/base.html",
    "content": "{% load static %}\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n    <title>Poll Me | Polls List</title>\n    <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\"\n        crossorigin=\"anonymous\">\n    <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\" integrity=\"sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/\"\n        crossorigin=\"anonymous\">\n\n    {% block custom_css %}{% endblock custom_css %}\n\n</head>\n\n<body>\n    {% include 'includes/navbar.html' %}\n\n    {% block content %}\n\n    {% endblock content %}\n\n\n    <!-- All javascript files goes under here    -->\n    <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\"\n        crossorigin=\"anonymous\"></script>\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\"\n        crossorigin=\"anonymous\"></script>\n    <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\"\n        crossorigin=\"anonymous\"></script>\n\n</body>\n\n</html>"
  },
  {
    "path": "templates/home.html",
    "content": "{% extends 'base.html' %}\n{% load static %}\n{% block custom_css %}\n<link rel=\"stylesheet\" href=\"{% static 'css/home_style.css' %}\">\n{% endblock custom_css %}\n\n\n{% block content %}\n<div class=\"container\">\n    <div class=\"row\">\n        <div class=\"col\">\n            <div id=\"home-content\">\n                <h1>PollMe - Get Started!</h1>\n                <h3>Your Voice Matters!</h3>\n                <hr>\n                <a class=\"btn btn-light btn-lg\" href=\"{% url 'polls:list' %}\" role=\"button\">Get Started !</a>\n            </div>\n        </div>\n    </div>\n</div>\n{% endblock content %}"
  },
  {
    "path": "templates/includes/navbar.html",
    "content": "<nav class=\"navbar navbar-expand-sm navbar-light bg-light mb-5\">\n    <a class=\"navbar-brand\" href=\"{% url 'home' %}\"><i class=\"fas fa-person-booth\"></i></a>\n    <button class=\"navbar-toggler d-lg-none\" type=\"button\" data-toggle=\"collapse\" data-target=\"#collapsibleNavId\"\n        aria-controls=\"collapsibleNavId\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n        <span class=\"navbar-toggler-icon\"></span>\n    </button>\n    <div class=\"collapse navbar-collapse\" id=\"collapsibleNavId\">\n        <ul class=\"navbar-nav mr-auto mt-2 mt-lg-0\">\n            <li class=\"nav-item active\">\n                <a class=\"nav-link\" href=\"{% url 'home' %}\">Home <span class=\"sr-only\">(current)</span></a>\n            </li>\n            {% if request.user.is_authenticated %}\n            <li class=\"nav-item\">\n                <a class=\"nav-link\" href=\"{% url 'polls:list' %}\">Polls</a>\n            </li>\n            {% endif %}\n        </ul>\n        <div class=\"navbar-nav ml-auto\">\n            {% if request.user.is_authenticated %}\n            <a class=\"nav-link\" href=\"{% url 'polls:list_by_user' %}\">My Polls</a>\n            <a class=\"nav-link\" href=\"{% url 'accounts:logout' %}\">Logout</a>\n            {% else %}\n            <a class=\"nav-link\" href=\"{% url 'accounts:login' %}\">Login</a>\n            <a class=\"nav-link\" href=\"{% url 'accounts:register' %}\">Register</a>\n            {% endif %}\n        </div>\n    </div>\n</nav>"
  }
]