1. 개발 환경 만들기
python3 -m venv myvenv
source myvenv/bin/activate
pip install django
django-admin startproject firstproject
cd firstproject
python manage.py startapp wordCount
2. settings.py에 앱 추가(wordCount의 apps.py의 클래스 이름을 추가)
'wordCount.apps.WordCountConfig',
1. 문장을 입력받을 템플릿만들기 --> templates/home.html
<div style="text-align: center">
<h1>WordCount 페이지 입니다.</h1>
<br>
<h3>여기에 문장을 입력해주세요.</h3>
<form action="result">
<textarea name="sentence" cols="60" rows="30 "></textarea>
<br><br>
<input type="submit" value="제출">
</form>
</div>
2. wordCount/views.py의 함수 작성
from django.shortcuts import render
def home(request):
render(request, "home.html")
3. url 연결 : firstproject/urls.py
from django.contrib import admin
from django.urls import path
from wordCount import views as wc
urlpatterns = [
path('admin/', admin.site.urls),
path('wc/', wc.home, name="wc"),
]
4. 결과를 보여줄 새로운 템플릿 생성 : templates/result.html
<템플릿 언어 : html에서 파이썬 변수와 문법을 사용하게 해주는 언어>
<div style="text-align: center">
<h2>입력한 텍스트 전문</h2>
<div>
{{fulltext}}
</div>
<h3>당신이 입력한 텍스트는 {{count}}개의 단어로 구성되어 있습니다.</h3>
<div>
{% for word, totalCount in wordDict %}
{{word}} : {{totalCount}}}
<br>
{% endfor %}
</div>
</div>
5. views.py 작성
from django.http import request
from django.shortcuts import render
def home(request):
return render(request, "home.html")
def result(requset):
sentence = request.GET['sentence']
wordList = sentence.split()
wordDict = {}
for word in wordList:
if word in wordDict:
wordDict[word] += 1
else:
wordDict[word] = 1
return render(request, "reqult.html", {'fulltext':sentence, 'count':len(wordList), 'wordDict': wordDict.items})
6. urls.py 수정
from django.contrib import admin
from django.urls import path
from wordCount import views as wc
urlpatterns = [
path('admin/', admin.site.urls),
path('wc/', wc.home, name="wc"),
path('wc/result/', wc.result, name="result"), #추가
]
7. 서버 실행
--> 이전과 똑같이 views.py에서 에러가 난다.
name 'request' is not defined
빠른 수정을 통해 수정을 하면 또 module 'django.http.request' has no attribute 'GET' 에러가나다. 이전에도 GET 때문에 에러가 났다.
'Back-end > Django' 카테고리의 다른 글
[Django] Django와 데이터베이스 (0) | 2021.07.19 |
---|---|
[Django] Git 사용법 (0) | 2021.07.19 |
[Django] Django 실습1 (0) | 2021.07.15 |
[Django] MTV 패턴 (0) | 2021.07.15 |
Django Setting (0) | 2021.07.15 |
댓글