Introduction
As a budding Django developer, creating my first CRUD (Create, Read, Update, Delete) operation was a significant milestone. This blog post will walk you through the steps I took to achieve this, providing a clear and concise guide for beginners.
Setting Up the Project
Create a New Django Project:
django-admin startproject my_project
Create a New App:
cd my_project
python manage.py startapp my_app
Creating the Model
Define the Model:
In my_app/models.py
, create a model to represent the data you want to manage:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
Migrate the Changes:
python manage.py makemigrations my_app
python manage.py migrate
Creating the Views
Create the Views: In my_app/views.py
, create views for each CRUD operation:
Python
from django.shortcuts import render, redirect
from .models import MyModel
def create_view(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
form.save()
return redirect('list_view') 1. github.com github.com
else:
form = MyModelForm()
return render(request, 'my_app/create.html', {'form': form})
# ... (similar views for read, update, and delete)
Access the Views: Visit the URLs you defined in your browser to test the CRUD operations.
Conclusion
By following these steps, you've successfully created your first CRUD operation with Django. This is a fundamental building block for many web applications. You can now expand upon this by adding more features, customizing the templates, and implementing additional functionality.