Creating an app in Django is a straightforward process. Here’s a step-by-step guide:
1. Set Up Your Django Project (If Not Already Done)
Ensure you have a Django project set up. If you don’t, create one:
django-admin startproject myproject
cd myproject
Note: Replace myproject
with your desired project name.
2. Create a New Django App
Run the following command to create a new app:
python manage.py startapp myapp
Replace myapp
with the name of your app. This will create a folder structure like:
myapp/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
3. Register the App in the Project
Add your new app to the INSTALLED_APPS
section in your project’s settings.py
:
INSTALLED_APPS = [
# Default apps...
'myapp', # Add your app here
]
4. Define Models (Optional)
Open models.py
in your app and define your data models:
from django.db import models
class ExampleModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
Run the following commands to create and apply migrations for your model:
python manage.py makemigrations
python manage.py migrate
5. Create Views
Define a view in views.py
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, world!")
6. Configure URLs
Create a urls.py
file in your app if it doesn’t exist, and add your view:
from django.urls import path
from . import views
urlpatterns = [
path('', views.hello_world, name='hello_world'),
]
In your project’s main urls.py
, include the app’s URLs:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')), # Include app URLs
]
7. Run the Server
Start the development server:
python manage.py runserver
Visit http://127.0.0.1:8000/myapp/ in your browser to see your app in action.