2.4 User URL 및 View 설정
Django에서 URL을 작성할 때는,
- Pattern
- Mapping
- URL 패턴 정의:
- urls.py 파일에 URL 패턴을 정의하여 뷰와 연결
from django.urls import path
from . import views
urlpatterns = [
path('', views.sign_up, name='sign_up'),
]
뷰(View) 작성:
views.py 파일에 뷰를 작성하여 요청을 처리하고, 데이터를 템플릿에 전달
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup_view(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login') # 회원가입 성공 시 로그인 페이지로 이동
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
2.5 템플릿 작성
1. 템플릿 파일 생성:
- templates 디렉토리를 만들고, 그 안에 HTML 파일을 작성
<!-- sign_up.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">회원가입</button>
</form>
2. 템플릿 경로 설정:
- settings.py 파일에서 템플릿 디렉토리 경로를 설정. 기본적으로 설정되어 있으나, 필요시 커스터마이징 가능
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# ... other settings ...
},
]
'Daily note' 카테고리의 다른 글
Today I Learned(TIL)-47 (2) | 2024.08.30 |
---|---|
Today I Learned(TIL)-45 (2) | 2024.08.28 |
Today I Learned(TIL)-43 (0) | 2024.08.26 |
Today I Learned(TIL)-42 (0) | 2024.08.22 |
Today I Learned(TIL)-40 (0) | 2024.08.21 |