Django’s philosophy of “Don’t Repeat Yourself” (DRY) encourages developers to write modular and reusable code. One effective way to achieve this is by creating reusable apps — self-contained components that can be easily integrated into different projects. In this tutorial, we’ll walk through the process of building a reusable app in Django using a simple example.
Step 1: Set Up Your Django Project
Assuming you have Django installed, start by creating a new project:
django-admin startproject myproject
cd myproject
Step 2: Create a Reusable App
Inside your project directory, create a new app:
python manage.py startapp myapp
Step 3: Define Models in Your Reusable App
In myapp/models.py
, define the models for your app. For this example, let's create a Book
model:
# myapp/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
def __str__(self):
return self.title
Step 4: Create Views and Templates
Now, create views and templates for your app. In myapp/views.py
, define a simple view to display a list of books:
# myapp/views.py
from django.shortcuts import render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'myapp/book_list.html', {'books': books})
Create a template in myapp/templates/myapp/book_list.html
:
<!-- myapp/templates/myapp/book_list.html -->
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }}</li>
{% endfor %}
</ul>
</body>
</html>
Step 5: Create URLs
Define the URLs for your app in myapp/urls.py
:
# myapp/urls.py
from django.urls import path
from .views import book_list
app_name = 'myapp'
urlpatterns = [
path('books/', book_list, name='book_list'),
]
Step 6: Include the App URLs in Your Project
Include the URLs from your app in myproject/urls.py
:
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
Read the full article here:
https://espere.in/Building-Reusable-Apps-in-Django:-A-Step-by-Step-Guide/