Django URLS, how to map root to app?

后端 未结 7 979
迷失自我
迷失自我 2021-01-30 08:43

I am pretty new to django but experienced in Python and java web programming with different frameworks. I have made myself a nice little django app, but I cant seem to make it m

相关标签:
7条回答
  • 2021-01-30 09:17

    I also wanted to have the root of my domain to directly point to a view of a sub app.

    At first I created the sub app with this command:

    python3 manage.py startapp main offer_finder/main
    

    In your case it would be:

    python3 manage.py startapp myApp project/somedirectory/myApp
    

    make sure that the directory exists: mkdir -p project/somedirectory/myApp

    This is my project structure: Project structure

    In my case I have these directories:

    offer_finder_project/offer_finder/main        # sub app  
    offer_finder_project/offer_finder/            # main source directory  
    

    in offer_finder_project/offer_finder/urls.py I have this code:

    from django.contrib import admin
    from django.urls import path, include
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('offer_finder.main.urls')),
    ]
    

    And in offer_finder_project/offer_finder/main/urls.py I have this code:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.index),
    ]
    

    And the offer_finder_project/offer_finder/main/views.py file simply contains some test code.

    from django.http import HttpResponse
    
    def index(request):
        return HttpResponse("TEST app index")
    

    This way your requests to your root domain are directed to your sub app. Hopefully this helps someone. This code was tested with Django 2.1.4.

    0 讨论(0)
提交回复
热议问题