Creating the Best TODO app With the Django Master [pt.2]

Creating the Best TODO app With the Django Master [pt.2]

This is the second Part of multipart Blog, in this Blog, we will be Looking at the V of MVT architecture of Django.

What is V?

V stands for Views, a View in Django is a function that is used to Generate a Response for a request. Views are written in views.py and are mapped to specific URLs in urls.py.

  1. Create Urls.py inside your "home" directory.

  2. Your Functions will be Written in the views.py

  3. Create a Forms.py inside your "home" directory. Your directory Structure should look like this:

  4. Create a class named "TaskForm" inside your forms.py like so

     from django.forms import ModelForm
     from .models import Task
    
     class TaskForm(ModelForm):
         class Meta:
             model = Task
             fields=['title','expires']
    
  5. Create a function named createtask that takes request as a parameter, saves the TaskForm if the request method is POST else just returns some stuff like shown. all of the .html files we are rendering to are called templates which will be the topic of the next blog from the Django Master

     from django.shortcuts import render,redirect
     from .forms import TaskForm
    
     def createtask(request):
         if request.method == 'POST':
             form = TaskForm(request.POST)
    
             if form.is_valid():
                 form.save()
                 return redirect('home')
         else:
             form = TaskForm()
             context={
                 'form':form
             }
         return render(request,'home/createtask.html',context)
    
  6. Create a function named togglestatus that will toggle the Boolean value in the "complete" field of Task Model like so

     from django.shortcuts import redirect
     def togglestatus(request,task_id):
         task = Task.objects.get(id=task_id)
         if task.complete==True:
             task.complete=False
         else:
             task.complete=True
         task.save()
         return redirect('home')
    
  7. Create list called urlpatterns and map the function to the routes like this.

     from django.urls import path
     from .import views
    
     urlpatterns = [
         path('',views.index,name='home'),
         path('createtask/',views.createtask,name='createtask'),
         path('togglestatus/<int:task_id>/',views.togglestatus,name='togglestatus')
     ]
    

    The name property in the Path() will help us immensely in Templates by just having to remember the name of the URL instead of the whole path. we will use this name by using the {% url 'name' %} in the next Blog

    In the next Blog we will see how the T in MVT architecture works in Django. Till Then, Keep Misinforming People

Did you find this article valuable?

Support Nischal lamichhane by becoming a sponsor. Any amount is appreciated!