Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Marc's Django-Todo solution #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
venv/
.venv/
.vscode/
__pycache__/
*.py[cod]
15 changes: 15 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todoapp.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)
10 changes: 10 additions & 0 deletions seeds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from todo.models import Todo

t1 = Todo(title="Wash dogs", description="Wash them with shampoo")
t1.save()

t2 = Todo(title="Cut grass", description="Mow, weed, edge, and blow before it rains this week")
t2.save()

t3 = Todo(title="Sweep", description="Sweep the hardwood floors")
t3.save()
Empty file added todo/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions todo/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
5 changes: 5 additions & 0 deletions todo/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class TodoConfig(AppConfig):
name = 'todo'
22 changes: 22 additions & 0 deletions todo/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 2.1.3 on 2021-07-12 20:38

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Todo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('description', models.CharField(max_length=200)),
],
),
]
Empty file added todo/migrations/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions todo/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.db import models

# Create your models here.
class Todo(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=200)

def __str__(self) -> str:
return f"ID: {self.id} Title: {self.title}"
5 changes: 5 additions & 0 deletions todo/templates/todo/todo_confirm_delete.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<h1>Todo Delete</h1>
<form method="post">{% csrf_token %}
Are you sure you want to delete "{{ object.title }}" ?
<input type="submit" value="Submit" />
</form>
18 changes: 18 additions & 0 deletions todo/templates/todo/todo_detail.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>

<h1>Todo Details</h1>
<h2>Title: {{ todo.title }}</h2>
Description: {{ todo.description }}
<hr/>
<a href="{% url 'todo:todo_list' %}">Back</a>

</body>
</html>
5 changes: 5 additions & 0 deletions todo/templates/todo/todo_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<h1>Todo Form: {{ new_or_edit }}</h1>
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
38 changes: 38 additions & 0 deletions todo/templates/todo/todo_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Todo List</h1>

<table border="1">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for todo in all_todos %}
<tr>
<td>{{ todo.title }}</td>
<td>{{ todo.description }}</td>
<td><a href="{% url 'todo:todo_view' todo.id %}">view</a></td>
<td><a href="{% url 'todo:todo_edit' todo.id %}">edit</a></td>
<td><a href="{% url 'todo:todo_delete' todo.id %}">delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>

<a href="{% url 'todo:todo_new' %}">New</a>

</body>
</html>
3 changes: 3 additions & 0 deletions todo/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
12 changes: 12 additions & 0 deletions todo/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from django.urls import path
from . import views

app_name = 'todo'

urlpatterns = [
path('', views.todo_list, name='todo_list'),
path('<int:todo_id>', views.todo_view, name='todo_view'),
path('new', views.todo_create, name='todo_new'),
path('<int:todo_id>/edit', views.todo_update, name='todo_edit'),
path('<int:todo_id>/delete', views.todo_delete, name='todo_delete'),
]
47 changes: 47 additions & 0 deletions todo/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from django.shortcuts import render, redirect
from django.forms import ModelForm

from todo.models import Todo

# Create your views here.
class TodoForm(ModelForm):
class Meta:
model = Todo
fields = ['title', 'description']

def get_todo(todo_id):
return Todo.objects.get(id=todo_id)


def todo_list(request):
todos = Todo.objects.all()
data = { 'all_todos': todos}
return render(request, 'todo/todo_list.html', data)


def todo_view(request, todo_id):
todo = get_todo(todo_id)
data = {'todo': todo}
return render(request, 'todo/todo_detail.html', data)

def todo_create(request):
form = TodoForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('todo:todo_list')
return render(request, 'todo/todo_form.html', {'form': form, 'new_or_edit': 'New'})

def todo_update(request, todo_id):
todo = get_todo(todo_id)
form = TodoForm(request.POST or None, instance=todo)
if form.is_valid():
form.save()
return redirect('todo:todo_list')
return render(request, 'todo/todo_form.html', {'form' :form, 'new_or_edit': 'Edit'})

def todo_delete(request, todo_id):
todo = get_todo(todo_id)
if request.method=='POST':
todo.delete()
return redirect('todo:todo_list')
return render(request, 'todo/todo_confirm_delete.html', {'object':todo})
Empty file added todoapp/__init__.py
Empty file.
121 changes: 121 additions & 0 deletions todoapp/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""
Django settings for todoapp project.

Generated by 'django-admin startproject' using Django 2.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hi%ycvw$8^dw--z!@3cw2g7%yezmtf0bvl^fs*b1*!a%9f!8$$'

# 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',
'todo'
]

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 = 'todoapp.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 = 'todoapp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'todo_db'
}
}


# Password validation
# https://docs.djangoproject.com/en/2.1/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/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
7 changes: 7 additions & 0 deletions todoapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('todo/', include('todo.urls'))
]
16 changes: 16 additions & 0 deletions todoapp/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for todoapp 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/2.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todoapp.settings')

application = get_wsgi_application()