Creating App in Django Project

Saprunov Vadim·2022년 6월 5일
0

Django

목록 보기
2/2

What is the difference between app and project?

In Django, every functionality of the webpage is separated into apps. (e.g., authentication, checkout, payment and etc.)
So a project would be the combination of such apps in one website.

To create a Django app:

python manage.py startapp appname

Ensure you are in the same dir where the manage.py file is located!

This command created the app folder.

Let's take a closer look at the files:

  1. As you already know, the init.py file needs to be here just to tell python that this folder is a package folder.
  2. Admin.py file takes care of the connection between your models and the Django Admin web interface.
  3. Apps.py is the application configuration file.
  4. Tests.py file is responsible for handling tests. This file is used in Test-driven development approach.
  5. Models.py is a more critical file for beginners because you will generate your objects here. Each model maps to a single Database table and contains all information about a particular thing.
  6. Views.py is basically the file responsible for displaying the requested webpage to the user.

Basic setup of the application

Application-level setup

First of all, your application has to respond to requests a user makes. To do so, you should create a basic function in Views.py.

from django.http import HttpResponse

def index(request):
	return HttpResponse("Hello, world")

Django applications have to know the route of the URLs inside the app. So you have to generate the urls.py file inside the application folder.

In urls.py, you have to write the following code:

from django.urls import path
from . import views

urlpatterns = [
	path('', views.index, name='index'),
]

Now your app knows that if the user requests the index webpage, it should respond with the function in the views.py file.

Project level setup

Each application in the project would have its own urls.py configuration file. So to "Plug" this file into your project-level urls.py configuration file, you have to include the app's urls.py in the project urls.py, like so:

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

urlpatterns = [
	path('helloworldapp/', inclue('helloworldapp.urls')),
    path('admin/', admin.site.urls),
]

now, if you run the server and navigate into:

localhost:8000/your-app-name

You should be able to see the response of your basic application!

profile
Python, Django, AI, OCR.

0개의 댓글