Consolidate forms for task creation and editing

This commit is contained in:
Scot Hacker 2018-03-24 12:24:49 -07:00
parent bc8adb63f5
commit 07e02b56f7
6 changed files with 128 additions and 177 deletions

View file

@ -19,16 +19,17 @@ class AddTaskListForm(ModelForm):
exclude = [] exclude = []
class AddItemForm(ModelForm): class AddEditItemForm(ModelForm):
"""The picklist showing the users to which a new task can be assigned """The picklist showing the users to which a new task can be assigned
must find other members of the groups the current list belongs to.""" must find other members of the groups the current list belongs to."""
def __init__(self, task_list, *args, **kwargs): def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.fields['assigned_to'].queryset = get_user_model().objects.filter(groups__in=[task_list.group]) self.fields['assigned_to'].queryset = get_user_model().objects.filter(groups__in=user.groups.all())
self.fields['assigned_to'].label_from_instance = lambda obj: "%s (%s)" % (obj.get_full_name(), obj.username) self.fields['assigned_to'].label_from_instance = lambda obj: "%s (%s)" % (obj.get_full_name(), obj.username)
self.fields['assigned_to'].widget.attrs = { self.fields['assigned_to'].widget.attrs = {
'id': 'id_assigned_to', 'class': "custom-select mb-3", 'name': 'assigned_to'} 'id': 'id_assigned_to', 'class': "custom-select mb-3", 'name': 'assigned_to'}
self.fields['task_list'].value = kwargs['initial']['task_list'].id
due_date = forms.DateField( due_date = forms.DateField(
widget=forms.DateInput(attrs={'type': 'date'}), required=False) widget=forms.DateInput(attrs={'type': 'date'}), required=False)
@ -44,22 +45,6 @@ class AddItemForm(ModelForm):
exclude = [] exclude = []
class EditItemForm(ModelForm):
"""The picklist showing the users to which a new task can be assigned
must find other members of the groups the current list belongs to."""
def __init__(self, *args, **kwargs):
super(EditItemForm, self).__init__(*args, **kwargs)
self.fields['assigned_to'].queryset = get_user_model().objects.filter(
groups__in=[self.instance.task_list.group])
due_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), required=False)
class Meta:
model = Item
exclude = ('created_date', 'created_by',)
class AddExternalItemForm(ModelForm): class AddExternalItemForm(ModelForm):
"""Form to allow users who are not part of the GTD system to file a ticket.""" """Form to allow users who are not part of the GTD system to file a ticket."""

View file

@ -0,0 +1,54 @@
{# Form used by both Add Task and Edit Task views #}
<form action="" name="add_task" method="post">
{% csrf_token %}
<div id="AddEditTask" class="collapse mt-3">
<div class="form-group">
<label for="id_title" name="title">Task</label>
<input type="text" class="form-control" id="id_title" name="title" required placeholder="Task title"
value="{% if form.title.value %}{{ form.title.value }}{% endif %}">
</div>
<div class="form-group">
<label for="id_note">Description</label>
<textarea class="form-control" id="id_note" name="note" rows="5"
aria-describedby="inputNoteHelp">{% if form.note.value %}{{ form.note.value }}{% endif %}</textarea>
<small id="inputNoteHelp" class="form-text text-muted">
Describe the task or bug. Provide steps to reproduce the issue.
</small>
</div>
<div class="form-group">
<label for="id_due_date">Due Date</label>
<input type="date" class="form-control" id="id_due_date" name="due_date"
value="{% if form.due_date.value %}{{ form.due_date.value|date:"Y-m-d" }}{% endif %}">
</div>
<div class="form-group">
<label for="id_assigned_to">Assigned To</label>
{# See todo.forms.AddItemForm #}
{{form.assigned_to}}
</div>
<div class="form-group">
<label for="id_notify">Notify</label>
<input type="checkbox" checked="checked" class="form-control" id="id_notify" name="notify" aria-describedby="inputNotifyHelp"
value="{{ form.notify.text }}">
<small id="inputNotifyHelp" class="form-text text-muted">
Email notifications will only be sent if task is assigned to someone other than yourself.
</small>
</div>
<input type="hidden" name="priority"
value="{% if form.priority.value %}{{ form.priority.value }}{% else %}999{% endif %}" id="id_priority">
<input type="hidden" name="created_by" value="{{ request.user.id }}" id="id_created_by">
<input type="hidden" name="task_list" value="{{ form.task_list.value }}" id="id_task_list">
<input type="hidden" name="created_date" value="{{ created_date }}" id="id_created_date">
<p>
<input type="submit" name="add_edit_task" value="Submit" class="btn btn-primary">
</p>
</div>
</form>

View file

@ -6,49 +6,11 @@
{% block content %} {% block content %}
{% if list_slug != "mine" %} {% if list_slug != "mine" %}
<form action="" name="add_task" method="post"> <button class="btn btn-primary" id="AddTaskButton" type="button"
{% csrf_token %} data-toggle="collapse" data-target="#AddEditTask">Add Task</button>
<button class="btn btn-primary" id="AddTaskButton" type="button" {# Task edit / new task form #}
data-toggle="collapse" data-target="#AddTask">Add Task</button> {% include 'todo/include/task_edit.html' %}
<div id="AddTask" class="collapse mt-3">
<div class="form-group">
<label for="id_title" name="title">Task</label>
<input type="text" class="form-control" id="id_title" name="title" required placeholder="Task title" value="{{ form.title.text }}">
</div>
<div class="form-group">
<label for="id_note">Description</label>
<textarea class="form-control" id="id_note" name="note"
rows="5" aria-describedby="inputNoteHelp">{{ form.note.text }}</textarea>
<small id="inputNoteHelp" class="form-text text-muted">Describe the task or bug. Provide steps to reproduce the issue.</small>
</div>
<div class="form-group">
<label for="id_due_date">Due Date</label>
<input type="date" class="form-control" id="id_due_date" name="due_date" value="{{ form.due_date.text }}">
</div>
<div class="form-group">
<label for="id_assigned_to">Assigned To</label>
{# See todo.forms.AddItemForm #}
{{form.assigned_to}}
</div>
<div class="form-group">
<label for="id_notify">Notify</label>
<input type="checkbox" checked="checked" class="form-control" id="id_notify" name="notify" aria-describedby="inputNotifyHelp" value="{{ form.notify.text }}">
<small id="inputNotifyHelp" class="form-text text-muted">Email notifications will only be sent if task is assigned to someone other than yourself.</small>
</div>
<input type="hidden" name="priority" value="999" id="id_priority">
<input type="hidden" name="created_by" value="{{ request.user.id }}" id="id_created_by">
<input type="hidden" name="task_list" value="{{ task_list.id }}" id="id_task_list">
<input type="hidden" name="created_date" value="{{ created_date }}" id="id_created_date">
<p><input type="submit" name="add_task" value="Submit" class="btn btn-primary"></p>
</div>
</form>
<hr /> <hr />
{% endif %} {% endif %}
@ -74,6 +36,7 @@
<th>Comm</th> <th>Comm</th>
<th>Del</th> <th>Del</th>
</tr> </tr>
{% for task in items %} {% for task in items %}
<tr id="{{ task.id }}"> <tr id="{{ task.id }}">
<td> <td>
@ -112,6 +75,7 @@
</table> </table>
<input type="submit" name="process_tasks" value="Process selection" class="btn btn-sm btn-success"> <input type="submit" name="process_tasks" value="Process selection" class="btn btn-sm btn-success">
{% include 'todo/include/toggle_delete.html' %} {% include 'todo/include/toggle_delete.html' %}
</form> </form>

View file

@ -1,6 +1,7 @@
{% extends "todo/base.html" %} {% extends "todo/base.html" %}
{% block title %}{{ list_title }} Todo Lists{% endblock %} {% block title %}{{ list_title }} Todo Lists{% endblock %}
{% block content %} {% block content %}
<h1>Todo Lists</h1> <h1>Todo Lists</h1>

View file

@ -4,6 +4,9 @@
{% block content %} {% block content %}
<button class="btn btn-primary" id="EditTaskButton" type="button"
data-toggle="collapse" data-target="#AddEditTask">Edit Task</button>
<div class="card-deck"> <div class="card-deck">
<div class="card col-sm-8"> <div class="card col-sm-8">
<div class="card-body"> <div class="card-body">
@ -15,88 +18,44 @@
</div> </div>
<div class="card col-sm-4"> <div class="card col-sm-4">
<ul class="list-group list-group-flush"> <ul class="list-group list-group-flush">
<li class="list-group-item"> <li class="list-group-item">
<strong>Assigned to:</strong> <strong>Assigned to:</strong>
{% if task.assigned_to %} {% if task.assigned_to %} {{ task.assigned_to.get_full_name }} {% else %} Anyone {% endif %}
{{ task.assigned_to.get_full_name }} </li>
{% else %} <li class="list-group-item">
Anyone <strong>Reported by:</strong> {{ task.created_by.get_full_name }}
{% endif %} </li>
</li> <li class="list-group-item">
<li class="list-group-item"> <strong>Due date:</strong> {{ task.due_date }}
<strong>Reported by:</strong> {{ task.created_by.get_full_name }} </li>
</li> <li class="list-group-item">
<li class="list-group-item"> <strong>Completed:</strong> {{ task.completed|yesno:"Yes,No" }}
<strong>Due date:</strong> {{ task.due_date }} </li>
</li> <li class="list-group-item">
<li class="list-group-item"> <strong>In list:</strong>
<strong>Completed:</strong> {{ task.completed|yesno:"Yes,No" }} <a href="{% url 'todo:list_detail' task.task_list.id task.task_list.slug %}">
</li> {{ task.task_list }}
<li class="list-group-item"> </a>
<strong>In list:</strong> </li>
<a href="{% url 'todo:list_detail' task.task_list.id task.task_list.slug %}"> </ul>
{{ task.task_list }}
</a>
</li>
</ul>
</div>
</div>
<button id="slideToggle" class="mt-3 btn btn-primary">Edit task</button>
{% comment %} Needs form tag {% endcomment %}
<div id="TaskEdit">
<h3>Edit Task</h3>
<table>
<tr>
<td>Title:</td>
<td>{{ form.title }}
</td>
</tr>
<tr>
<td>List:</td>
<td>{{ form.task_list }}
</td>
</tr>
<tr>
<td>Due:</td>
<td>{{ form.due_date }}
</td>
</tr>
<tr>
<td>Assigned to:</td>
<td>{{ form.assigned_to }}
</td>
</tr>
<tr>
<td valign="top">Note:</td>
<td>{{ form.note }}
</td>
</tr>
<tr>
<td>Priority:</td>
<td>{{ form.priority }}
</td>
</tr>
</table>
<p><input type="submit" class="btn btn-primary" name="edit_task" value="Edit task"></p>
</div> </div>
<hr/> </div>
<h3>Add comment</h3> <div id="TaskEdit">
<textarea name="comment-body"></textarea> {# Task edit / new task form #}
<p><input class="btn btn-primary" type="submit" value="Submit"></p> {% include 'todo/include/task_edit.html' %}
</div>
<h3>Add comment</h3>
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" name="comment-body" rows="3"></textarea>
</div>
<input class="btn btn-primary" type="submit" name="add_comment" value="Add Comment">
</form>
<div class="task_comments"> <div class="task_comments">
{% if comment_list %} {% if comment_list %}
@ -116,17 +75,3 @@
</div> </div>
{% endblock %} {% endblock %}
{% block extra_js %}
<script type="text/javascript">
$(document).ready(function () {
// Initially hide the TaskEdit form
$('#TaskEdit').hide();
// toggle slide to show the Add Task form when link clicked
$('#slideToggle').click(function () {
$(this).siblings('#TaskEdit').slideToggle();
});
});
</script>
{% endblock extra_js %}

View file

@ -14,7 +14,7 @@ from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from todo import settings from todo import settings
from todo.forms import AddTaskListForm, AddItemForm, EditItemForm, AddExternalItemForm, SearchForm from todo.forms import AddTaskListForm, AddEditItemForm, AddExternalItemForm, SearchForm
from todo.models import Item, TaskList, Comment from todo.models import Item, TaskList, Comment
from todo.utils import ( from todo.utils import (
toggle_done, toggle_done,
@ -126,10 +126,11 @@ def list_detail(request, list_id=None, list_slug=None, view_completed=False):
# Add New Task Form # Add New Task Form
# ###################### # ######################
if request.POST.getlist('add_task'): if request.POST.getlist('add_edit_task'):
form = AddItemForm(task_list, request.POST, initial={ form = AddEditItemForm(request.user, request.POST, initial={
'assigned_to': request.user.id, 'assigned_to': request.user.id,
'priority': 999, 'priority': 999,
'task_list': task_list
}) })
if form.is_valid(): if form.is_valid():
@ -144,9 +145,10 @@ def list_detail(request, list_id=None, list_slug=None, view_completed=False):
else: else:
# Don't allow adding new tasks on some views # Don't allow adding new tasks on some views
if list_slug not in ["mine", "recent-add", "recent-complete", ]: if list_slug not in ["mine", "recent-add", "recent-complete", ]:
form = AddItemForm(task_list=task_list, initial={ form = AddEditItemForm(request.user, initial={
'assigned_to': request.user.id, 'assigned_to': request.user.id,
'priority': 999, 'priority': 999,
'task_list': task_list
}) })
context = { context = {
@ -174,33 +176,33 @@ def task_detail(request, task_id: int) -> HttpResponse:
if task.task_list.group not in request.user.groups.all() and not request.user.is_staff: if task.task_list.group not in request.user.groups.all() and not request.user.is_staff:
raise PermissionDenied raise PermissionDenied
if request.POST: # Save submitted comments
form = EditItemForm(request.POST, instance=task) if request.POST.get('add_comment'):
Comment.objects.create(
author=request.user,
task=task,
body=request.POST['comment-body'],
)
send_email_to_thread_participants(request, task)
messages.success(request, "Comment posted. Notification email sent to thread participants.")
# Save task edits
if request.POST.get('add_edit_task'):
form = AddEditItemForm(request.user, request.POST, instance=task, initial={'task_list': task.task_list})
if form.is_valid(): if form.is_valid():
form.save() form.save()
# Also save submitted comment, if non-empty
if request.POST['comment-body']:
c = Comment(
author=request.user,
task=task,
body=request.POST['comment-body'],
)
c.save()
send_email_to_thread_participants(request, task)
messages.success(request, "Notification email sent to thread participants.")
messages.success(request, "The task has been edited.") messages.success(request, "The task has been edited.")
return redirect('todo:list_detail', list_id=task.task_list.id, list_slug=task.task_list.slug) return redirect('todo:list_detail', list_id=task.task_list.id, list_slug=task.task_list.slug)
else: else:
form = EditItemForm(instance=task) form = AddEditItemForm(request.user, instance=task, initial={'task_list': task.task_list})
if task.due_date:
thedate = task.due_date if task.due_date:
else: thedate = task.due_date
thedate = datetime.datetime.now() else:
thedate = datetime.datetime.now()
context = { context = {
"task": task, "task": task,