Editing tasks - 30 days of Django

Editing tasks - 30 days of Django

/ #Django

Let's learn more about forms and how to create an edit form for the tasks.

We are actually just going to continue to use the same form as earlier, but I want a separate view and template for editing the tasks.

Let's begin with the template. Create a new file (called edit_task.html) in the same folder as the frontpage.html. It should look like this:

{% extends 'task/base.html' %}

{% block content %}
    <div class="edit-tasks">
        <h1>Edit task</h1>

        <form method="post" action=".">
            {% csrf_token %}

            {{ form.as_p }}

{% endblock %}

Hopefully, all of the code here looks familiar, and that you understand it?
We don't need to do anything more here in the template. Django will fill out the form and similar, based on the data we provide it from the view.

If we open up task/views.py again, we can create the view for editing tasks:

from django.shortcuts import render, redirect # 1, New


def edit_task(request, pk):
    task = Task.objects.get(pk=pk)

    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)

        if form.is_valid():

            return redirect('frontpage')
        form = TaskForm(instance=task)
    return render(request, 'task/edit_task.html', {'form': form})

First, we import a new shortcut from Django called "redirect". This will be used for redirecting the user back to the front page after the task is saved. I added three dots "..." just to show you that the other imports and the frontpage view can be like they were.

The code inside this view is more or less the same as the frontpage. We check the request method, and create a form based on this. The main difference is the instance parameter that we pass in. This is to make sure that Django know that we are editing a task. So since we passed in this parameter, Django will automatically fill the form for us and also make sure the task is updated and not created.

Before we can use this, we also need to append the view to "task/urls.py" like this:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.frontpage, name='frontpage'),
    path('edit_task/<int:pk>/', views.edit_task, name='edit_task'), # New

This should look familiar. It's just a simple primary key inside the path, and then we point to the view. Next and last step is to update template to link to this path. In the loop where we show the tasks, do this:

{% for task in tasks %}
            {{ task.title }}
            <a href="{% url 'edit_task' task.id %}">Edit</a>
{% endfor %}

And that was it, this was everything we needed to do to make it possible to edit tasks.

Table of contents


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.