Home Backend Development Python Tutorial CRUD Operations In Python & Django - Part 2

CRUD Operations In Python & Django - Part 2

Jul 25, 2024 pm 03:17 PM

In our previous article, we covered the basics of setting up a Django project and created our Exercise model, which we displayed on the front end as a list. In this article, we’ll dive into performing CRUD operations. For those unfamiliar, CRUD stands for Create, Read, Update, and Delete—essentially the four fundamental actions you can perform on your data.

Now that we have our API set up in the app folder, we’ll simply extend the index view to handle create, update, and delete requests.

The Form

Let’s set up a form that allows users to create exercises. We’ll be using HTML templates for this purpose once again. To get started, create a new template called add_exercise.html in the app/templates folder.

<form method="POST" action="/">
    {% csrf_token %}
    <input type="text" name="title" placeholder="Enter the title" />
    <input type="date" name="date"  placeholder="Enter the date" />
    <button type="submit">Save</button>
</form>
Copy after login

Next, in our index.html template, we’ll include the add_exercise.html template using the following method:

{% extends "base.html" %} {% block content %}
    <h2>Exercises</h2>
    {% include 'add_exercise.html' %}
...
{% endblock %}
Copy after login

We’re utilizing the include tag here, which promotes composability across HTML templates, making our code easier to maintain and understand. If you refresh the page in your browser, you should see the form appear on the screen.

Add Exercise

In our HTML, we're using the 

 tag with the method attribute set to POST and the action attribute pointing to /, which is the same endpoint we use to fetch the list of exercises.

In this context, the csrf_token is a security feature represented by a randomly generated secret value. It helps protect our form submissions from forgery attacks, which is what CSRF stands for—Cross-Site Request Forgery. A unique token is generated for each user session, and it is not accessible by third-party sites, thereby preventing unauthorised changes from occurring.

Our form includes two input fields: one for the title and another for the date, following the schema of our Exercise model. When the form is submitted, the values for title and date will be sent via a POST request to the / endpoint, which will then be processed by our index view in app/views.py.

The Model

In Django, we can enhance our Exercise model—essentially a Python class—by adding specific methods that correspond to CRUD operations. In the app/models.py file, we’ll include the following:

class Exercise(models.Model):
    ...

    def create(request):
        title = request.POST.get('title')
        date = request.POST.get('date')

        exercise = Exercise.objects.create(title=title, date=date)

        return exercise
Copy after login

We can access title and date from the POST request, as shown in the code above. Then, we can utilize Django's built-in ORM to create a new exercise and return the created instance.

We'll leverage the same index view we use to retrieve exercises, expanding it to check if the request method is POST. If so, we'll pass the request object to the class method we previously defined. Once the exercise is created, we'll redirect the user back to the homepage or perform a page refresh, ensuring the newly added exercise appears on the screen.

from django.http import HttpResponseRedirect

from app import models

...

def index(request):
    if request.method == 'POST':
        models.Exercise.create(request)
        return redirect('/')

    exercises = (
        models.Exercise.objects.all().order_by("created_at")
    )
    return render(request, "index.html", context={'exercises': exercises})
Copy after login

Try creating a new exercise now, and you should see it appear at the bottom of the list.

Update Exercise

Let's refactor our code a bit before adding update functionality to the exercises. We'll move the exercises to their own template called exercise.html.

<h2>Exercises</h2>
{% include 'add_exercise.html' %}
<ul style="margin: 0; list-style: none; padding: 0">
    {% for exercise in exercises %}
        <li style="margin-top: 4px">
            {% include 'exercise.html' %}
        </li>
    {% endfor %}
</ul>
Copy after login

Create a template for exercise.html in the app/templates folder, and we’ll add the following HTML to it:

<form method="POST" action="/">
    {% csrf_token %}
    <input hidden name="id" value="{{exercise.id}}" />
    <input
        type="text"
        name="title"
        value="{{exercise.title}}"
        placeholder="Enter the title"
    />
    <input
        type="date"
        name="date"
        placeholder="Enter the date"
        value="{{exercise.date | date:'Y-m-d'}}"
    />
    <button type="submit" name="update">Update</button>
</form>
Copy after login

We’re using the  tag again for each exercise in the list and adding a hidden input for exercise.id, which will be used to update the exercise. Go back to the browser and refresh the page; you should see a form for each exercise in the list, with each input pre-filled with the corresponding exercise data.

CRUD Operations In Python & Django - Part 2

Notice that we’re not using PUT as the form method; instead, we’re using POST. This is because the view handlers can only parse data sent through GET and POST requests, with no built-in support for PUT and DELETE. When we created the create class method in the Exercise class, you might have noticed we used request.POST.get('title'). While this works for POST requests, there are no PUT or DELETE methods available in the request object.

But how do we differentiate between a POST and a PUT request? If you check the form we created earlier, you’ll notice that we assigned a name attribute to the submit button. We can access this attribute in the same way we accessed title and date, using request.POST.get('update').

Let's update the create exercise form to include the same change.

<form method="POST" action="/">
    ...
    <button type="submit" name="create">Save</button>
</form>
Copy after login

And in our exercises view, we’ll make the following changes to differentiate between requests.

def index(request):
    if request.method == 'POST':
        create = 'create' in request.POST
        update = 'update' in request.POST

        if create == True:
            models.Exercise.create(request)
        elif update == True:
            models.Exercise.update(request)

        return redirect('/')

    exercises = (
        models.Exercise.objects.all().order_by("created_at")
    )
    return render(request, "index.html", context={'exercises': exercises})
Copy after login

We check for the button name and forward the request to the appropriate Exercise method accordingly.

Let's add an update class method to the Exercise model in app/models.py.

def update(request):
    id = request.POST.get('id')
    title = request.POST.get('title')
    date = request.POST.get('date')

    exercise = Exercise.objects.filter(pk=id).update(title=title, date=date)

    return exercise
Copy after login

To update a row in the database, we can use the update method available on the Exercise model. However, before updating, we need to ensure that we are updating the correct exercise. To do this, we filter the exercises by the primary key, which is id, and update only that specific exercise.

Delete Exercise

Similarly, we’ll add a delete button next to each exercise in the exercise.html template.

<form method="POST" action="/">
    ...
    <button type="submit" name="update">Update</button>
    <button type="submit" name="delete">Delete</button>
</form>
Copy after login

We’ll set delete as the value of the name attribute, and in views.py, we’ll extend the if...elif statements to handle the delete operation.

def index(request):
    if request.method == 'POST':
        create = 'create' in request.POST
        update = 'update' in request.POST
        delete = 'delete' in request.POST

        if create == True:
            models.Exercise.create(request)
        elif update == True:
            models.Exercise.update(request)
        elif delete == True:
            models.Exercise.delete(request)

        return redirect('/')

    exercises = (
        models.Exercise.objects.all().order_by("created_at")
    )
    return render(request, "index.html", context={'exercises': exercises})
Copy after login

And in the Exercise model, we'll add the class method delete.

def delete(request):
    id = request.POST.get('id')
    is_deleted = Exercise.objects.filter(pk=id).delete()

    if is_deleted == 1:
        return True

    return False
Copy after login

With this addition, we've successfully implemented CRUD operations in our Python and Django application.

Key Takeaways

  1. Django view handlers do not support PUT and DELETE requests, as they do not parse the query parameters or request body for those HTTP methods. As a result, we must rely on POST requests and differentiate between them by passing an additional field in the request body.
  2. Noticed that I'm making the POST request to the same route from which I'm fetching the exercises. This is important because if you were to create an endpoint like /api/exercises to handle requests, you would need to manage redirection manually. Otherwise, the behavior of the tag after the request is to redirect the user to the endpoint specified in the action attribute. Therefore, you will need to manually redirect the user back to the desired page, or in our case, keep the user on the same page.
from django.http import HttpResponseRedirect

def index(request):
    ...

    return redirect('/')
    # or
    return HttpResponseRedirect(request.META['HTTP_REFERER'])
Copy after login

In summary, by effectively managing our POST requests and ensuring proper redirection, we can create a seamless user experience while implementing CRUD operations in our Django application.

The above is the detailed content of CRUD Operations In Python & Django - Part 2. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles