InterviewSolution
| 1. |
How to create a simple application in Django? |
|
Answer» We are assuming here that the project is created and database connection is set up, and you are in a project folder. Your Djong application can be anywhere on your Python path. Here, we’ll CREATE our app RIGHT next to your manage.py FILE so that it can be imported as its own top-level module, rather than a submodule of mysite. To create an application, make sure you’re in the same directory here manage.py and type this command: $ python manage.py startapp newappIt will create a directory newapp, which would look like − newapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.pyApplication newapp will house in this directory structure. Now to write view open newapp/views.py file and update with below lines - from django.http import HTTPRESPONSE def index(request): return HttpResponse("Hello, world")To call this view, you NEED to map it to a URL. Create URLconf in the newapp directory, create a file called urls.py. Your directory should look like - newapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.pyUpdate urls.py file with the following code - //urls.py from django.urls import path from.import views urlpatterns = [ path('', views.index, name='index'),]Now point the root_URLconf at the newapps.urls module. In newsite/urls.py, import Django.urls.include and insert an include() in the urlpatterns list. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('newapps/', include('newapps.urls')), path('admin/', admin.site.urls),] |
|