Task Create Module
Steps to Develop a Task Create module.
1. Create template for Task Create module.
templates/todo/task_form.html
{% extends 'todo/main.html' %}
{% block content %}
<div class="header-bar">
<a href="{% url 'tasks' %}">← Back</a>
</div>
<div class="card-body">
<form method="POST" action="">
{% csrf_token %}
{{form.as_p}}
<input class="button" type="submit" value="Submit">
</form>
</div>
{% endblock content %}
2. Create view function for Task Create module
Import Statements:
from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .models import Task # Import your Task model
These statements import the necessary classes for creating a Task Create view and applying the LoginRequiredMixin.
Class Definition:
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)
Here's a breakdown of the code:
TaskCreate
is a class-based view for creating tasks.It inherits from
LoginRequiredMixin
, which ensures that only logged-in users can access this view.The
model
attribute is set to theTask
model, indicating that this view is used for creating instances of theTask
model.The
fields
attribute specifies the fields from theTask
model that will be included in the form. In this case, it includes 'title', 'description', and 'complete'.The
success_url
attribute is set to the URL to redirect to after the form is successfully submitted. In this case, it's set to the URL named 'tasks' usingreverse_lazy
.The
form_valid
method is overridden to set theuser
field of the task to the current logged-in user before saving the form.self.request.user
represents the user who made the request.form.instance
represents the instance of the model form before it's saved.
This code ensures that a new task is associated with the currently logged-in user when it is created.
3. Mapping URLs to Task Create view.
Make sure you have the necessary URLs and other configurations in place to use this Task Create view. For example, in your urls.py
file, you might have something like:
from django.urls import path
from .views import TaskCreate
urlpatterns = [
path('task-create/', TaskCreate.as_view(), name='task-create'),
# Add other URL patterns as needed
]
4. Update the task_list.html
add href value to line no. 18 and 49 in task_list.html
href="{% url 'task-create' %}"
5. Run the development server to check the functionality:
Start the development server if it's not running already:
python manage.py runserver
Access the interface by visiting http://localhost:8000/task-create
in your web browser.
Output:

Last updated