한 걸음씩
[Django] 로또 번호 생성 프로젝트 본문
1. 가장 먼저 해야할 것 : urls.py 파일 코드 작성
# urls.py
from articles import views
urlpatterns = [
path('admin/', admin.site.urls),
path('lotto-create/', views.lotto_create, name='lotto-create'),
path('lotto/', views.lotto),
]
# name 부분은 lotto.html파일에서 바로가기 버튼 눌렀을 때 원래 페이지로 돌아가기 위해서 만듦
2. view.py 파일에서 html파일로 넘길 로또 번호를 생성할 함수 만들기
# views.py
# 로또 번호 생성기
def lotto_create(request):
return render(request, 'lotto_create.html')
def lotto(request):
# count는 lotto-create로부터 입력받은 수인데 정수 변환해줘야 함(str오류)
count = int(request.GET.get('count'))
# lottos는 랜덤으로 뽑아낼 6자리 수
# range(1, 46)이 범위 안에서 6자리 추출 후 오름차순 정렬
# sample은 원하는 개수만큼 뽑아냄
lottos = [sorted(sample(range(1, 46), 6)) for _ in range(count)]
# lottos = []
# for _ in range(count):
# numbers = sample(range(1, 46),6)
# lotto = sorted(numbers)
# lottos.append(lotto)
return render(request, 'lotto.html', {'lottos': lottos})
# lottos는 타입에러발생 -> 딕셔너리형태로 전달해야함{'lottos': lottos}
# render함수는 템플릿에 context를 전달함.
# context는 딕셔너리 형태로 전달되고, 템플릿에서 사용할 수 있는 변수들을 담고 있음
# 딕셔너리의 각 key-value 쌍에서 key는 템플릿에서 사용될 변수의 이름이고, value는 실제 값
# 따라서 'lottos'라는 변수를 사용하기 위해서는 {'lottos': lottos}라는 context를 전달해야 함
# context = {'lottos': lottos} 와 {'lottos': lottos}은 같은 의미, 단지 변수에 저장했냐 안했냐의 차이
3. base.html 파일은 중복되는 요소를 줄이기 위해 만든 부모 템플릿
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Base-document</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous"
/>
</head>
<body>
{% block content %}{% endblock content %}
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
crossorigin="anonymous"
></script>
</body>
</html>
4. 아래 두 html파일은 base.html파일의 자식 템플릿
- 로또 번호 생성 수를 작성할 폼을 만들 lotto_create.html파일, 부트스트랩 사용함
<!-- lotto_create.html -->
{% extends 'base.html' %}
{% block content %}
<form action="/lotto/" method="GET" class="input-group mt-5 mx-5 w-25 p-3">
<input type="number" name="count" placeholder="로또 생성수" class="form-control" />
<button type="submit" class="btn btn-outline-secondary">생성</button>
</form>
{% endblock content %}
5. lotto.html파일은 '생성' 버튼을 눌렀을 때 6자리 로또 번호가 생성되는 페이지
- pre태그를 통해 for문에서 나오는 요소들을 개행시켜줌
- a 태그의 url참조할때 장고의 {% url 'name' %} 기능을 사용하여 lotto_create.html페이지로 돌아갈 수 있도록 함
<!-- lotto.html -->
{% extends 'base.html' %} {% block content %}
<div class="mt-5 ms-5">
{% for lotto in lottos %}
<pre>{{ lotto }} </pre>
{% endfor %}
<a href="{% url 'lotto-create' %}">뒤로가기</a>
</div>
{% endblock content %}
'Django' 카테고리의 다른 글
[Django] Django URLS (0) | 2023.03.23 |
---|---|
[Django] 템플릿 경로 지정 BASE_DIR (0) | 2023.03.22 |
[Django] Django Template (0) | 2023.03.22 |
[Django] Django design pattern (0) | 2023.03.21 |
django shell_plus (0) | 2023.03.21 |