Our task is to create a simple ToDo app using Django that allows users to add, view, and delete notes. We will build this by setting up a Django project, creating a Todo model, designing forms and views to handle user input, and creating templates to display the tasks. Step-by-step, we'll implement the core functionality to manage todo items efficiently.
Basic setup
Create a virtual environment, and install the packages:
pip install django-crispy-forms
pip install Django
Step 1: Create a Django Project
Start a new Django project namedtodo_site: This sets up the base project directory and files (settings, URLs, etc.) to start building your Django application.
django-admin startproject todo_site
Step 2: Navigate to the Project Directory
cd todo_site
Step 3: Create a Django App
Create an app named todo where the core logic of your ToDo app (models, views, forms, etc.) will reside.
python manage.py startapp todo
The directory structure should look like this:
Project DirectoryStep 4: Add the todo App to Settings
Opentodo_site/settings.py and add'todo' to theINSTALLED_APPSlist: Register the todo app so Django includes it in migrations, admin panel, and more.
settings.pyStep 5: Configure URLs
Edittodo_site/urls.py to include the todo app views: This connects your app’s views to specific URLs—/ for the list and /del/<id> to delete items.
Pythonfromdjango.contribimportadminfromdjango.urlsimportpathfromtodoimportviewsurlpatterns=[path('',views.index,name="todo"),path('del/<str:item_id>',views.remove,name="del"),path('admin/',admin.site.urls),]
Step 6: Define the ToDo Model
Edittodo/models.py to define the Todo model. The model represents each to-do item with a title, description, and creation time.
Pythonfromdjango.dbimportmodelsfromdjango.utilsimporttimezoneclassTodo(models.Model):title=models.CharField(max_length=100)details=models.TextField()date=models.DateTimeField(default=timezone.now)def__str__(self):returnself.title
Step 7: Create Views
Edittodo/views.py:
- index() shows the task list and handles new submissions.
- remove() deletes a task by ID.
These views interact with the model and render templates with context data.
Pythonfromdjango.shortcutsimportrender,redirectfromdjango.contribimportmessagesfrom.formsimportTodoFormfrom.modelsimportTododefindex(request):item_list=Todo.objects.order_by("-date")ifrequest.method=="POST":form=TodoForm(request.POST)ifform.is_valid():form.save()returnredirect('todo')form=TodoForm()page={"forms":form,"list":item_list,"title":"TODO LIST",}returnrender(request,'todo/index.html',page)defremove(request,item_id):item=Todo.objects.get(id=item_id)item.delete()messages.info(request,"item removed !!!")returnredirect('todo')
Step 8: Create a Form
Create todo/forms.py and add the following:
Pythonfromdjangoimportformsfrom.modelsimportTodoclassTodoForm(forms.ModelForm):classMeta:model=Todofields="__all__"
This form handles user input using Django’sModelForm, automatically generating fields from the model.
Step 9: Register the Model with Admin
Edit todo/admin.py to register the Todo model:
Pythonfromdjango.contribimportadminfrom.modelsimportTodoadmin.site.register(Todo)
Registering the model allows you to manage to-do items via Django’s built-in admin interface.
Step 10: Create the Template
Create the foldertodo/templates/todo/ and add index.html:
HTML<!DOCTYPE html><htmllang="en"dir="ltr"><head><metacharset="utf-8"><title>{{title}}</title><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><!--style--><style>.card{box-shadow:04px8px0rgba(0,0,0,0.5),06px20px0rgba(0,0,0,0.39);background:lightpink;margin-bottom:5%;border-radius:25px;padding:2%;overflow:auto;resize:both;text-overflow:ellipsis;}.card:hover{background:lightblue;}.submit_form{text-align:center;padding:3%;background:pink;border-radius:25px;box-shadow:04px8px0rgba(0,0,0,0.4),06px20px0rgba(0,0,0,0.36);}</style></head><bodyclass="container-fluid"> {% if messages %} {% for message in messages %}<divclass="alert alert-info"><strong>{{message}}</strong></div> {% endfor %} {% endif %}<centerclass="row"><h1><i>__TODO LIST__</i></h1><hr/></center><divclass="row"><divclass="col-md-8"> {% for i in list %}<divclass="card"><center><b>{{i.title}}</b></center><hr/> {{i.date}}<hr/> {{i.details}}<br/><br/><formaction="/del/{{i.id}}"method="POST"style=" padding-right: 4%; padding-bottom: 3%;"> {% csrf_token %}<buttonvalue="remove"type="submit"class="btn btn-primary"style="float: right;"><spanclass="glyphicon glyphicon-trash"></span> remove</button></form></div> {% endfor%}</div><divclass="col-md-1"></div><divclass="col-md-3"><divclass="submit_form"><formmethod="POST"> {% csrf_token %} {{forms}}<center><inputtype="submit"class="btn btn-default"value="submit"/></center></form></div></div></div></body></html>
This HTML file:
- Displays all tasks with their details.
- Shows a form for adding new tasks.
- Includes delete buttons using POST for CSRF protection.
- Uses Bootstrap for styling.
Step 11: Apply Migrations
Create and apply migrations to set up the database schema:
python manage.py makemigrations
python manage.py migrate
Step 12: Run the Development Server
Start the Django development server:
python manage.py runserver
Open your web browser and go to http://127.0.0.1:8000/ to see your ToDo app in action!
Output:
To Do webAppToDo List Application in Django