Request comes to web server ➜ passed onto Django for analysis
client requests a URL (ex. codecademy.com) ➜ Django takes URL and pass it to its urlresolver ➜ try to match the URL to a list of patterns & if there is a match ➜ pass request to the associated view function
lands on the right page ➜ Django uses data from model ➜ feedts it into the view function to determine what data is shown ➜ data is then given to the template ➜ presented to the client via web page
django-admin <command> [options]
django-admin help
= provide a list of possible commandsdjango-admin startproject projectname
= will create a project. ⚡️ Inside, we find manage.py
= collection of useful functions to administer the project
django-admin
but specifically for the project⚡️ We also find my_project
, a directory with the same name as the project
__init__.py
.
사용?INSTALLED_APPS
: contains the apps that make up the Django projectDATABASES
: shows the database connection details in a dictionary formInside are the URL declarations for this Django project, or a “table of contents” for the Django project.
Remember earlier when we said that Django goes down a list of patterns to match a URL? This is that list!
python3 manage.py runserver <port number>
manage.py
is located. ctrl + c
.migration
= models.py
에서 바꾼 내용을 (예를 들면 field를 추가하거나, model을 삭제하는 것 등) 데이터베이스 스키마에 전파시키는
장고의 방법이다settings.py
에서 봤듯이, Django는 이미 설치된 app 들이 있다.Whenever we make changes to the model of the database, we must apply the changes by running
python3 manage.py migrate
.The migrate command will update database models for projects installed in
INSTALLED_APPS
.
After applying the migration:
localhost/admin
to see the successful admin login page❓ What are Django apps? Difference between app and project?
manage.py
가 들어있고, settings.py
가 들어있는 파일도 있다. 반면에, app에는 models.py
와 test.py
다 들어있다.예시)
Project : website for a vet office
Apps : an appointment calendar, patient profiles, a testimonial section
python3 manage.py startapp myapp
manage.py
가 있는 곳)models.py
나 test.py
같은 각각의 app만을 위한 파일들이 들어있다.INSTALLED_APPS
in the settings.py
fileviews.py : a class or function that processes a request and sends a response back - decides what data gets delivered to a template and displayed
Example)
In our veterinarian’s office example website, a customer might go to the /profile
page of the website and their request gets passed to a view function to be processed. The view function may:
➤ In Django, requests, and responses are handled as HttpRequest
and HttpResponse
objects from a module called django.http
.
from django.http import HttpResponse
불러와줘야 한다
When a page is requested,
HttpRequest
object that contains information about the requestHttpRequest
as the first argument to the view function➤ Each view function is responsible for returning an HttpResponse
object. The HttpResponse
response object can be the HTML contents of a web page, a redirect, an error, an XML document, an image, or just about anything that can display on a web page.
💡 정리하자면,
Django가 request 정보가 담긴HttpRequest
object를 만들어서 적절한 view를 불러오고, 그 view function에HttpRequest
를 첫번째 인자로 통과시킨다.
그리고 나서, view는HttpResponse
object를 리턴한다. 리턴하는건 컨텐츠나 이미지 등 웹페이지에 보여질 수 있는 거의 모든것이다.
➤ view function은 이렇게 생겼다:
# In views.py def index(request): return HttpResponse("This is the response!")
홈페이지를 방문하면, 이
index()
view function이 string이 들어간HttpResponse
를 리턴한다 (이 string이 웹페이지에 보여지게 된다)
위에서는 그냥 텍스트만 브라우저에게 보냈다.
하지만 웹사이트는 그렇게 단순하지 않다. HTML
view function을 부르게 되면, Django는 INSTALLED_APPS
안에 있는 어플의 폴더들을 하나하나 흝으면서 templates
라는 디렉토리를 찾는다. 하지만 그렇게되면 template라는 폴더가 여러개있어서 헷갈리기 때문에,
일반적으로, 우리는 URL Namespacing하는 convention을 통해 여러 앱들 사이에서 구분을 하게 한다.
app_name = 'polls'
라고 선지정을 해주고,templates/
directory.templates/
디렉토리 안에, app이랑 같은 디렉토리(폴더)안에다가 넣어준다.이렇게 되면 우리의 views.py
는:
from django.template import loader
def home():
template = loader.get_template("app/home.html")
return HttpResponse(template.render())
django.template
에서 loader
을 import 한다home()
이라는 view function 안에 get_template()
을 통해 template을 로드한다HttpResponse
object 안에 있는 template object 에다가 .render()
메소드를 사용해서 클라이언트에게 HTML page를 보여준다.name/value pair
. views.py:
from django.http import HttpResponse
from django.template import loader
def home(request):
context = {"name": "Junior"}
template = loader.get_template("app/home.html")
return HttpResponse(template.render(context))
render()
사용:
from django.shortcuts import render
def home(request):
context = {"name": "Junior"}
return render(request, "app/home.html", context)
render()
takes 3 arguments:
1. request object
2. path to the template
3. context (dictionary that passes the context variables to the template)
URLConf = set of patterns that Django will try to match the requested URL to find the correct view
urls.py
Import
path
object from django.urls
views.py
urlpatterns
path()
object that has three arguments:''
, the home()
view function will be called. Going to the URL ending with /profile
will call the profile()
view function.from django.urls import path
from . import views
>
urlpatterns = [
path('', views.home),
path('profile/', views.profile, name="profile")
]
default urls.py
folder:
#default urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path("admin/", admin.site.urls), ] # app's URLconf added from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("myapp.urls")), ]
urlpatterns
. The admin page we visited earlier is already there: path('admin/', admin.site.urls)
urls.py
.django.urls
and add a path()
to the urlpatterns
.