Repository: divanov11/Django-To-Do-list-with-user-authentication Branch: master Commit: d798a5917279 Files: 28 Total size: 23.2 KB Directory structure: gitextract_eb3yuwfd/ ├── .gitignore ├── Pipfile ├── README.md ├── base/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations/ │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20210322_2234.py │ │ └── __init__.py │ ├── models.py │ ├── templates/ │ │ └── base/ │ │ ├── login.html │ │ ├── main.html │ │ ├── register.html │ │ ├── task.html │ │ ├── task_confirm_delete.html │ │ ├── task_form.html │ │ └── task_list.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py └── todo_list/ ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py media # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # /staticfiles/ ### Django.Python Stack ### # Byte-compiled / optimized / DLL files *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ pytestdebug.log # Translations *.mo # Django stuff: # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ doc/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry #poetry.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments # .env .env/ .venv/ env/ venv/ ENV/ env.bak/ venv.bak/ pythonenv* # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # operating system-related files *.DS_Store #file properties cache/storage on macOS Thumbs.db #thumbnail cache on Windows # profiling data .prof ================================================ FILE: Pipfile ================================================ [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "*" [requires] python_version = "3.8" ================================================ FILE: README.md ================================================ # Django-To-Do-list-with-user-authentication To Do list app with User Registration, Login, Search and full Create Read Update and DELETE functionality. ![DEMO](../master/Django%20To%20Do%20List%20App.jpg) ================================================ FILE: base/__init__.py ================================================ ================================================ FILE: base/admin.py ================================================ from django.contrib import admin from .models import Task admin.site.register(Task) ================================================ FILE: base/apps.py ================================================ from django.apps import AppConfig class BaseConfig(AppConfig): name = 'base' ================================================ FILE: base/forms.py ================================================ from django import forms # Reordering Form and View class PositionForm(forms.Form): position = forms.CharField() ================================================ FILE: base/migrations/0001_initial.py ================================================ # Generated by Django 3.1.7 on 2021-03-22 16:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('description', models.TextField(blank=True, null=True)), ('complete', models.BooleanField(default=False)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-complete'], }, ), ] ================================================ FILE: base/migrations/0002_auto_20210322_2234.py ================================================ # Generated by Django 3.1.7 on 2021-03-22 17:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('base', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='task', options={}, ), migrations.AlterOrderWithRespectTo( name='task', order_with_respect_to='user', ), ] ================================================ FILE: base/migrations/__init__.py ================================================ ================================================ FILE: base/models.py ================================================ from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: order_with_respect_to = 'user' ================================================ FILE: base/templates/base/login.html ================================================ {% extends 'base/main.html' %} {% block content %}

Login

{% csrf_token %} {{form.as_p}}

Don't have an account? Register

{% endblock content %} ================================================ FILE: base/templates/base/main.html ================================================ To Do Items
{% block content %} {% endblock content %}
================================================ FILE: base/templates/base/register.html ================================================ {% extends 'base/main.html' %} {% block content %}

Register

{% csrf_token %} {{form.username}} {{form.password1}} {{form.password2}}

Already have an account? Login

{% endblock content %} ================================================ FILE: base/templates/base/task.html ================================================

Task: {{task}}

================================================ FILE: base/templates/base/task_confirm_delete.html ================================================ {% extends 'base/main.html' %} {% block content %}
← Go Back
{% csrf_token %}

Are your sure you want to delete this task? "{{task}}"

{% endblock content %} ================================================ FILE: base/templates/base/task_form.html ================================================ {% extends 'base/main.html' %} {% block content %}
← Back
{% csrf_token %} {{form.as_p}}
{% endblock content %} ================================================ FILE: base/templates/base/task_list.html ================================================ {% extends 'base/main.html' %} {% block content %}

Hello {{request.user|title}}

You have {{count}} incomplete task{{ count|pluralize:"s" }}

{% if request.user.is_authenticated %} Logout {% else %} Login {% endif %}
{% if tasks|length > 0 %} + {% endif %}
{% for task in tasks %}
{% if task.complete %}
{{task}} {% else %}
{{task}} {% endif %}
×  ⠇
{% empty %}

No new tasks are created.

Create a New task !

{% endfor %}
{% endblock content %} ================================================ FILE: base/tests.py ================================================ from django.test import TestCase # Create your tests here. ================================================ FILE: base/urls.py ================================================ from django.urls import path from .views import TaskList, TaskDetail, TaskCreate, TaskUpdate, DeleteView, CustomLoginView, RegisterPage, TaskReorder from django.contrib.auth.views import LogoutView urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('register/', RegisterPage.as_view(), name='register'), path('', TaskList.as_view(), name='tasks'), path('task//', TaskDetail.as_view(), name='task'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-update//', TaskUpdate.as_view(), name='task-update'), path('task-delete//', DeleteView.as_view(), name='task-delete'), path('task-reorder/', TaskReorder.as_view(), name='task-reorder'), ] ================================================ FILE: base/views.py ================================================ from django.shortcuts import render, redirect from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login # Imports for Reordering Feature from django.views import View from django.shortcuts import redirect from django.db import transaction from .models import Task from .forms import PositionForm class CustomLoginView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('tasks') class RegisterPage(FormView): template_name = 'base/register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterPage, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(RegisterPage, self).get(*args, **kwargs) class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count() search_input = self.request.GET.get('search-area') or '' if search_input: context['tasks'] = context['tasks'].filter( title__contains=search_input) context['search_input'] = search_input return context class TaskDetail(LoginRequiredMixin, DetailView): model = Task context_object_name = 'task' template_name = 'base/task.html' class TaskCreate(LoginRequiredMixin, CreateView): model = Task fields = ['title', 'description', 'complete'] success_url = reverse_lazy('tasks') def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreate, self).form_valid(form) class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task fields = ['title', 'description', 'complete'] success_url = reverse_lazy('tasks') class DeleteView(LoginRequiredMixin, DeleteView): model = Task context_object_name = 'task' success_url = reverse_lazy('tasks') def get_queryset(self): owner = self.request.user return self.model.objects.filter(user=owner) class TaskReorder(View): def post(self, request): form = PositionForm(request.POST) if form.is_valid(): positionList = form.cleaned_data["position"].split(',') with transaction.atomic(): self.request.user.set_task_order(positionList) return redirect(reverse_lazy('tasks')) ================================================ FILE: manage.py ================================================ #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_list.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() ================================================ FILE: todo_list/__init__.py ================================================ ================================================ FILE: todo_list/asgi.py ================================================ """ ASGI config for todo_list project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_list.settings') application = get_asgi_application() ================================================ FILE: todo_list/settings.py ================================================ """ Django settings for todo_list project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'd)=^c7!0-oqjmqve%(bt+p#sq6x*ipz2keh741j*-@f@_)f!1t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'todo_list.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'todo_list.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = 'login' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' ================================================ FILE: todo_list/urls.py ================================================ """todo_list URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), ] ================================================ FILE: todo_list/wsgi.py ================================================ """ WSGI config for todo_list project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_list.settings') application = get_wsgi_application()