Manage Multiple Django App in our Django Project

  • Here's an example of how you can manage multiple Django apps within a Django project:
  • Start by creating a new Django project using the `django-admin` command:

    django-admin startproject django_app

  • Inside the project directory (`django_app`), create two Django apps using the `manage.py` script:

    python manage.py startapp app1
    python manage.py startapp app2

  • Now, let's configure the project settings to include the newly created apps. Open the `settings.py` file inside the `django_app` directory and modify the `INSTALLED_APPS` list to include the apps:

    INSTALLED_APPS = [
        'app1',
        'app2',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

  • Next, create the necessary views and URLs for each app. In the respective app directories (`app1` and `app2`), create a new file called `views.py` and define some views. after creating the views, create URL configurations for each app. In the `app1` and `app2` directories, create a new file called `urls.py` and define the URLs:
  • django_app/urls.py

    from django.contrib import admin
    from django.urls import path, include

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

  • django_app/app1/views.py

    from django.http import HttpResponse

    def app1_view(request):
        return HttpResponse("This is app1!")

  • django_app/app1/urls.py

    from django.urls import path
    from .views import app1_view

    urlpatterns = [
        path('', app1_view, name='app1'),
    ]

  • django_app/app2/views.py

    from django.http import HttpResponse

    def app2_view(request):
        return HttpResponse("This is app2!")

  • django_app/app2/urls.py

    from django.urls import path
    from .views import app2_view

    urlpatterns = [
        path('', app2_view, name='app2'),
    ]

  • Finally, run the development server using the `manage.py` script:

    python manage.py runserver

  • You should now be able to access your Django project at `http://localhost:8000`. The URLs `/app1/` and `/app2/` will display the respective views from each app.
  • http://127.0.0.1:8000/app1/
  • http://127.0.0.1:8000/app2/
  • That's it! You have successfully managed multiple Django apps within a Django project.

No comments:

Post a Comment