How to create app in Django

Let’s create a simple Django app that displays “Hello World!” Step by step:

Step 1: Create a New Django Project

If you haven’t already, create a new Django project using the following command:

django-admin startproject projectname

Replace “projectname” with the name of your project.

Step 2: Create a New Django App

Now, create a new Django app within your project:

cd projectname
python manage.py startapp helloworld

This will create an app named “helloworld” in your project.

Step 3: Define a View

In the helloworld app directory, open the views.py file and define a view that will display “Hello World!”. Add the following code:

# helloworld/views.py
from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello World!")

Step 4: Create URL Configuration

In the same app directory, create a URL configuration for your view. Create a new file named urls.py if it doesn’t already exist, and add the following code:

# helloworld/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.hello_world, name='hello_world'),
]

Step 5: Configure the Project URL

In your project’s main urls.py (located in the project’s directory), include the URL patterns from your app by adding the following code:

# projectname/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('helloworld/', include('helloworld.urls')),
]

Step 6: Run the Development Server

Start the Django development server:

python manage.py runserver

Step 7: Access “Hello World!”

Open your web browser and navigate to http://127.0.0.1:8000/helloworld/hello/. You should see the text “Hello World!” displayed in your browser.

Congratulations! You’ve created a simple Django app that displays “Hello World!” For more concise guides and insights on various topics, visit AiHints.

Leave a Comment

Your email address will not be published.