공부일지

230313_django_html 반복문, static 및 완충용 가상환경 생성 본문

Computer/공부정리

230313_django_html 반복문, static 및 완충용 가상환경 생성

이르리의 공부일지 2023. 3. 13. 11:44

Back-end란...

 

웹 할 때는 항상 먼저 서버 잘 열리나 확인 >python manage.py runserver
html에서  프로그래밍할 때 {%  %} {% for 반복문 %}
...
{% endfor %}
html은 무조건 key값만 씀
따라서 원하는 데이터 형태.[key이름]
dict={"id":"a01", "pw":"pw01"}
ex. 
{{dict.id}}
{{dict.pw}}




 

예제1.

secondapp에서도 실행
1 views에 함수 정의 def tableFor2(request):
      col1={"id":"a01", "pw":"pw01"}
      col2={"id":"b02", "pw":"pw02"}
      col3={"id":"c03", "pw":"pw03"}

cols=[col1, col2, col3]

context={"lists":cols}

return render(request,
"secondapp/03_for.html",
context)
2 urls에서 urlpatterns에 path 추가 path("/tablefor2", views.tableFor2)
3 templates\secondapp에 html 구문 추가 >03_for.thml<

<table border='1'>


        <tr>
            <th>아이디</th>
            <th>패스워드</th>
        </tr>
        {% for dict in lists %}
<tr>
<td>{{dict.id}}</td>
<td>{{dict.pw}}</td>
</tr>
  {% endfor%}
</table>


 

 


 

 

 


예제2.
thirdapp 만들어서 해보기

tutorial2 > config   
config 있으니까 바로 앱 생성 [thirdapp] >django-admin startapp thirdapp
settings에 꼭 새로운 앱 추가

*안 하면 오류남
INSTALLED_APP=[

'thirdapp',

]
urls에 thirdapp의 urls추가 path('third/', include('thirdapp.urls'))
>thirdapp  
>views
def tableFor2(request):
    col1={"id":"a01", "pw":"pw01"}
    col2={"id":"b02", "pw":"pw02"}
    col3={"id":"c03", "pw":"pw03"}
   
    cols=[col1, col2, col3]
   
    context={"lists":cols}
   
    return render(request,
                  "thirdapp/03_for.html",
                  context)
>urls from . import views

path('tablefor2/', views.tableFor2)
새폴더 "templates\thirdapp" 생성 후 html 파일 생성
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>::: html에서 for문 사용 :::</title>
</head>
<body>
    <h3>HTML에서 for문 사용</h3>
    <table border='1'>
        <tr>
            <th>아이디</th>
            <th>패스워드</th>
        </tr>
        {% for dict in lists %}
            <tr>
                <td>{{ dict.id }}</td>
                <td>{{ dict.pw }}</td>
            </tr>
        {% endfor %}
    </table>
</body>
</html>

 

 

 


 

 

 

   
static 란 s, css, image, font 와 같이 개발자가 사전에 서버에 저장해둔 '정적인' 파일
=>static을 하기 위한 방법은 아래와 같다
>.html >독타입(<!DOCTYPE html>)) 아래에 

{% load static %}
> <head></head>안에  
images

=><img>삽입
<img src="{%static 'firstapp/images/dog01.png'%}"
css

=><link>삽입
<link href="{%static 'firstapp/css/09.css.css'%}
rel='stylesheet'
type='text/css">
js

=><script type='text/javascript'></script> 삽입
<srcipt type='text/javascript' src="{%static 'firstapp/js/js.js'%}">
</script>



 


 

 

예제 3. 

  • views : getJavascript() 생성
  • html : 06_js.html 생성
  • js 폴더에 js.js 파일 넣기
  • js : viewAlert() 생성=>alert("javascript 성공~!")
  • url : first/js

 

예제3 풀이

back-end : 연결

>views


def getJavasript(request):
return render(request, "firstapp/js/js.js", {})
>urls

urlpatterns에 path 추가
path('js/', views.getJavascript)

front-end : 보여줄 내용 작성

>templates/firstapp

06_js.html 생성
>독타입 선언 아래
{%load static%}


><head></head> 안에
<script type='text/javascript' src="{%static 'firstapp/js/js.js'%}">
</script>

><body></body> 안에
<button onclick="viewAlert()">클릭</button>
>static/firstapp/js

js.js 생성 : html문 안에서 보여줄 함수 선언

def viewAlert(){
alert("javascript 연결 성공~!");
}

 

 


 

 

가상환경 고장날 경우 대비해서 하나 더 만들어 놓자.

1. venv_django2 가상환경 만들기
2. 라이브러리 설치(기존과 동일)
3. django 라이브러리 설치까지
4. 기존의 tutorial2 폴더를 copy 후 tutorial3 이름으로 수정
5.venv_django2 가상환경에서 tutorial3가 잘 실행되는지 서버 실행해보기

 

 

요약 : 1~3까지 해주고, 기존에 만들어놨던 tutorial 폴더를 복사한 뒤 잘 실행되는지만 확인

 

※ tutorial 폴더는 매번 복사해두기(백업) to 깨질 경우 대비

 

 

 

mkdir venv2

cd venv2

버전 확인

python --version

가상환경 활성화

cd venv_django2

cd Scripts

activate.bat

cd /

cd venv2

cd venv_django2


파이썬 업글 

python -m pip install --upgrade pip

python install --upgrade setuptools

주피터 노트북 설치

pip install jupyter notebook

커널 연결

python -m ipykernel install --user --name venv_django2 --display-name venv_django2_kernel

커널 생성 확인

jupyter notebook

아니면

jupyter kernelspec list

라이브러리 설치(ML/DL, excel, Django for 빅데이터 분석 및 웹 서버 구축)

pip install ipython jupyter matplotlib pandas scikit-learn xlrd seaborn

pip install openpyxl 

pip install django==4.0.1


여까지 하고 tutorial 복사본 가져와서 되나 확인한다.
cd /

cd tutorial3

python manage.py runserver

확인 완료~!