[Django] URL 연결/버튼 클릭 시 페이지 이동

yukongs·2023년 8월 3일
0
post-thumbnail

🌐 앱에 기능 추가하기

Django가 설치되어 있는 가상환경(venv)프로젝트 폴더(islyweb)에서 아래 명령어를 입력해준다.

python manage.py startapp 기능이름
# ex. python manage.py startapp login

➕ 생성된 기능에 URL 연결하기

Django에서 프로젝트를 생성하면 폴더이름과 똑같은 폴더가 내부에 생성된다.
예를 들면, 해당 사진에서는 islyweb 폴더 내 동일한 이름의 폴더가 하나 더 생성되어 있음.

1. islyweb/islyweb/settings.py

내가 추가하고 싶은 기능을 아래에 추가해주면 된다.
로그인 기능을 만들었다고 치자.

INSTALLED_APPS = [
	'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'islyweb',
    'login',
    ]

이렇게 추가해줘야 장고가 기능을 하나의 앱(?) 단위로 인식해준다.

2. islyweb/templates/login/index.html

최상위폴더(islyweb) 아래에 templates 폴더가 없으면 하나 만들도록 하자.
templateshtml을 관리하는 폴더 이다. 하위엔 login 폴더를 하나 만들어주자.
login 기능과 관련된 html은 앞으로 islyweb/templates/login에서 관리하면 된다.
index.html을 하나 생성하여 아무 내용이나 입력해주자.

<!DOCTYPE html>
<html>
    <head>
        <title>hello</title>
    </head>
    <body>
	    <h1>Hello World!</h1>
    </body>
</html>

3. islyweb/login/views.py

from django.shortcuts import render
from rest_framework.views import APIView

class Login(APIView):
    def get(self, request):
        print("get으로 호출")
        return render(request, 'login/index.html')
    
    def post(self, request):
        print("post로 호출")
        return render(request, 'login/index.html')

django restframework 꼭 설치해주세요
^^

++ /login/kong/ 페이지 추가할 때 추가사항(수정 말고 추가)

class Kong(APIView):
    def get(self, request):
        print("get으로 호출")
        return render(request, 'login/kong.html')
    
    def post(self, request):
        print("post로 호출")
        return render(request, 'login/kong.html')

4. islyweb/login/urls.py

맨 처음 startapp을 사용해서 login 기능을 생성했던 게 기억나는가?
생성된 기능의 폴더는 최상위 폴더(islyweb) 내에 위치해 있을 건데, login폴더를 열어보면 urls.py가 없을 것이다. 이 폴더에 urls.py 를 하나 만들어주자. 아래 코드를 입력해준다.

from django.urls import path
from .views import Login

urlpatterns = [
    # url path: login/
    path('', Login.as_view()),
]

아 참, django restframework 꼭 설치해줘야 한다.
설치 방법은 어렵지 않으니까 구글링 ㄱ❗

++ url을 http://127.0.0.1:8000/login/kong 같이 뒤에 추가로 달고 싶으면
path('kong/', Kong.as_view()), 을 추가해주고 from .views import Login, Kong 하면 됨.

5. islyweb/islyweb/urls.py

from django.contrib import admin
from django.urls import path, include
from .views import Main
# all url
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', Main.as_view()),
    path('login/', include('login.urls')),
]

맨 아랫줄 꼬옥 추가해주기..

그럼 이제 끝! 한번 서버 구동해서 확인해보세요


+ django 서버 구동하기

python manage.py runserver

http://127.0.0.1:8000/login/

잘 접속되면 성공 ~

profile
보안/개발/대학생

1개의 댓글

comment-user-thumbnail
2023년 8월 3일

잘 읽었습니다. 좋은 정보 감사드립니다.

답글 달기