Creating a Simple CRUD App in Django
Django is a powerful web framework that makes it easy to build web applications quickly and efficiently. One common task in web development is creating a CRUD (Create, Read, Update, Delete) application. In this blog post, we will walk through the steps to create a simple CRUD app in Django.
Step 1: Setting up the Django project
First, make sure you have Django installed on your machine. You can install it using pip:
“`
pip install django
“`
Next, create a new Django project by running the following command in your terminal:
“`
django-admin startproject crud_app
“`
Navigate into the project directory:
“`
cd crud_app
“`
Step 2: Creating the Django app
Now, we will create a new Django app within our project. Run the following command in your terminal:
“`
python manage.py startapp myapp
“`
Then, add the new app to the installed apps in the settings.py file:
“`python
INSTALLED_APPS = [
…
‘myapp’,
]
“`
Step 3: Setting up the models
In Django, models are used to define the structure of your database tables. Open the models.py file in your app directory and define a simple model for our CRUD app:
“`python
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
“`
Don’t forget to run the migrations to create the database tables for your models:
“`
python manage.py makemigrations
python manage.py migrate
“`
Step 4: Creating the views
Next, we need to create the views for our CRUD app. Open the views.py file in your app directory and define the following views:
“`python
from django.shortcuts import render
from .models import Item
def index(request):
items = Item.objects.all()
return render(request, ‘index.html’, {‘items’: items})
“`
Step 5: Creating the templates
Create a new templates directory in your app directory and add an index.html file:
“`html
Items
-
{% for item in items %}
- {{ item.name }}
{% endfor %}
“`
Step 6: Testing the app
Finally, start the Django development server and navigate to http://localhost:8000 to see your CRUD app in action:
“`
python manage.py runserver
“`
That’s it! You have successfully created a simple CRUD app in Django. You can now expand on this app by adding more functionality such as editing and deleting items. Django’s built-in admin interface can also be used to manage your data easily. Happy coding!