View와 URL 연결하기🤪
Views : what information is being shown to the client
URLs : where that information is shown on the website
They work in concert so you can think of each View/URL pairing as a web page on the website.
✅How to connect a View to a URL
➡ path() 함수 사용해서!
매개변수 :
- route : String code the contains the URL pattern.
Django will scan the relevant urlpatterns list until it finds a matching string route
- view : Once a matching route is found, the view argument connects to a function or view, typically defined in the views.py file of the relevant Django app.
- kwargs(optional) : Allows us to pass in keyword arguments as a dictionary to the view.
- name(optiona) : Allows us to name a URL in order to referecne it elsewhere in Django.
Code Examples🤪:
my_site 프로젝트 내부의 my_app이란 애플리케이션의 view와 url을 연결하고 프로젝트 레벨 url로 연결하기.
#my_site > my_app > views.py
from django.shortcuts import render
from django.http.response import HttpResponse
# Create your views here.
def simple_view(request):
return HttpResponse("SIMPLE VIEW"); #TEMPLATE HTML (JINJA)
#my_site > my_app > urls.py
from django.urls import path
from . import views
#domain.com/my_app/
urlpatterns=[
path('simple_view',views.simple_view),
]
#my_site > my_site > urls.py
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path,include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('my_app/',include('my_app.urls')),
]