Django 프론트 환경 설정

정윤수·2022년 8월 3일
0

기초 명령어

  • urls.py : Router
  • views.py: Controller 느낌~~
source djangovenv/bin/activate  # 가상환경 실행
python3 manage.py runserver     # 서버 실행

django 에서의 render

  1. /accountapp 에 templates 폴더 생성
  2. /accountapp/templates/accountapp 폴더 생성
  3. /accountapp/templates/accountapp/temp.html 파일 생성
    1. https://github.com/noeul1114/pragmatic/blob/main/templates/temp.html

views.py

from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
# Create your views here.

def hello_world(requset):
    # html 탬플릿을 이용해서 응답을 주겠다.
    return render(requset, 'accountapp/temp.html')

settings.py


TEMPLATES = [
    {
				...
				'DIRS': [os.path.join(BASE_DIR, 'templates')],
		}
]

Git

  • git 설정
git init

git remote add origin [git repository 주소]
  • .env 설정

참고: https://pypi.org/project/django-environ/

# django-environ 설치   **(django env 관리 프로그램)**
pip install django-environ

# settings.py 

# from pathlib import Path 밑에
import environ
import os

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)

# Set the project base directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

...
SECRET_KEY = env('SECRET_KEY')

.env 파일

  • 변수와 값 사이에 공백이 없게 넣어야 한다!!
SECRET_KEY='django-insecure-m=j=tf!v6b1l4_8xz0)y@5&4-2y_5-my49ug_60q5b^^gw2u-@'
DEBUG=True

.gitignore


HTML, CSS

  • /templates 아래
    • base.html, head.html, header.html, footer.html 파일 생성

    • base.html

      # base.html
      <!DOCTYPE html>
      <html lang="ko">
        {% include 'head.html' %}
        <body>
          {% include 'header.html' %}
          <hr />
      
          {% block content %} {% endblock %}
      
          <hr />
          {% include 'footer.html' %}
        </body>
      </html>
    • head.html

    • 부트스트랩: https://getbootstrap.com/docs/5.2/getting-started/introduction/

    • 구글폰트: https://fonts.google.com/?preview.text=yoonsoo&preview.text_type=custom
      - 특정 폰트의 link 복붙 후, 원하는 곳엔 해당 css 복붙

      <head>
        <meta charset="UTF-8" />
        <title>Title</title>
      
        <!-- bootstrap -->
        <link
          href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx"
          crossorigin="anonymous"
        />
        <!-- GOOGLE FONT -->
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link
          href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap"
          rel="stylesheet"
        />
      </head>
    • header.html

      <div style="text-align: center; margin: 2rem 0">
        <div>
          <h1 style="font-family: 'Permanent Marker', cursive">Yoonsoo's Django</h1>
        </div>
        <div>
          <span>nav1</span>
          <span>nav1</span>
          <span>nav1</span>
          <span>nav1</span>
        </div>
      </div>
  • footer.html
<div
  style="
    text-align: center;
    margin-top: 2rem;
    font-family: 'Permanent Marker', cursive;
  "
>
  <div style="font-size: 0.6rem">
    <span>공지사항</span> | <span>제휴문의</span> |
    <span>서비스 소개</span>
  </div>

  <div style="margin-top: 1rem">
    <h6>Yoonsoo</h6>
  </div>
</div>
  • /accountapp/templates/accountapp 폴더 아래
    • hello_world.html 파일 생성

    • hello_world.html

      {% extends 'base.html' %} {% block content %}
      
      <div
        style="
          height: 10rem;
          background-color: #38df81;
          border-radius: 1rem;
          margin: 2rem;
        "
        ;
      >
        <h1>hi</h1>
      </div>
      
      {% endblock %}

css 적용하기

settings.py

  • templates 파일들이 어디로 모일 것인지 알려주는 거당
    • join : 합친다
    • BASE_DIR: 폴더(night) 경로의 staticfiles를 경로로 정하겠따

settings.py

...
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') 

# 앱에 종속되어 있지 않은 STATICFILES 를 따로 만들어줄거당
# 참고: https://docs.djangoproject.com/ko/4.0/howto/static-files/
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

footer.py

...
<div style="margin-top: 1rem">
    <h6 class="footer_logo">Yoonsoo</h6>
  </div>

/static 폴더 생성 → night/static/base.css

.footer_logo {
  font-family: "Permanent Marker", cursive;
}

/templates/head.html

  • settings.py 에 적어준 STATIC_URL 이랑 여기 적어준 base.css 이랑 연결돼서 작동하는 거야
{% load static %}

<head>
		...

<!-- DEFAULT CSS -->		
<link rel="stylesheet" type="text/css" href="{% static 'base.css' %}" />
</head>

display

  • block: 부모의 최대 넓이를 가져가는 (높이는 x) (한 줄에 하나만 대신 가득)
  • inline: 글씨의 높이 만큼만 한 줄내에 가져가는 (한 줄내에 자식 태그가 오른쪽으로 여러개 쌓이는)
  • inline-block: block인데도 자식 태그가 오른쪽으로 여러개 쌓이는
  • none: 아예 없도록 < - > hidden: 보이지만 않을 뿐, 존재는 하는

# hello_world.html

{% block content %}
...
	
	<h1> testing </h1>
	
	<div class="testing" style="display: block">block</div>
  <div class="testing" style="display: inline">inline</div>
  <div class="testing" style="display: None">None</div>
  <div class="testing" style="display: inline-block">inline-block</div>
  <div class="testing">default</div>
...
{% endblock %}

  • 지금까지 내용은 그냥 테스트였다. == 이전 커밋으로 다시 돌아가고 싶따
git reset --hard HEAD

$ git reset HEAD^ # 가장 최신 커밋 취소
$ git reset HEAD~3 #최신 커밋 3개 취소


Database

  • Row == Item
  • Columns == Attributes
  • Python 에서는 편한 ORM 을 제공해준당

accountapp/models.py

  • 아래 내용 입력 후, python3 manage.py makemigrations
  • 왜냐하면 models.py 에 쓴 내용을 DB 랑 연동 시키려고
  • 이거 하면 migrations 에 파일 생겨
from django.db import models

# Create your models here.

class HelloWorld(models.Model):
    text = models.CharField(max_length=255, null=False)
  • migrations 에 파일이 만들어지고 나서, 자동으로 연동되는게 아니라, 연동시켜주는 명령어를 또 다시 입력해줘야 돼ㅜㅠ. == 엑셀 파일에서 새로운 시트 만드는 거랑 비슷
  • 참고로 생성된 migrations 안에 파일은 최대한 안지우는 게 좋디
python3 manage.py migrate

HTTP protocol

  • GET, POST

views.py

def hello(request):

    if request.method == "POST":
        return render(request, 'accountapp/hello_world.html', context={'text': "POST METHOD!!!!"})
    else:
        return render(request, 'accountapp/hello_world.html', context={'text': "GET METHOD!!!!"})

accountapp/templates/accountapp/hello_world.html

  • csrf_token: python 에서 HTTP 요청 보낼때는, 보안상 토큰이 필요해서 국룰이담
  • btn btn-primary는 bootstrap
...
	<form action="/account/hello/" method="post">
    {% csrf_token %}
    <input type="submit" class="btn btn-primary" value="POST" />
  </form>
  <h1>{{ text }}</h1>
...

POST 요청으로 db 에 넣기

urls.py (Router)

from django.urls import path

from accountapp.views import hello, hello_world_drf

app_name = "accountapp"
urlpatterns = [

    path('hello/', hello, name="hello"),

]

views.py (Controller)

  • hello_world.html 에서의 input 내용을 가져와서 db에 저장시키는 방식
  • 빵 틀 (HelloWorld()에서) 가져온당
app_name = "accountapp"
# 기존 장고 방식
def hello(request):

    if request.method == "POST":

        temp = request.POST.get('hello_input')

        new_hello = **HelloWorld()**
        new_hello.text = temp
        new_hello.save()
        return render(request, 'accountapp/hello_world.html', context={'hello_db': new_hello})
    else:
        return render(request, 'accountapp/hello_world.html', context={'text': "GET METHOD!!!!"})

hello_world.html

<form action="/account/hello/" method="post">
    {% csrf_token %}
    <div>
      <input type="text" name="hello_input" />
    </div>
    <input type="submit" class="btn btn-primary" value="POST" />
  </form>

  {% if hello_db %}
  <h1>{{ hello_db.text }}</h1>
  {% endif %}

POST 요청으로 리스트 출력

  • HttpResponseRedirect(”accountapp/hello”) 도 가능하지만, 더 편하게~
  • 편하게 쓰려면 앞에 reverse 메서드
from django.urls import reverse

def hello(request):

    if request.method == "POST":

        temp = request.POST.get('hello_input')

        new_hello = HelloWorld()
        new_hello.text = temp
        new_hello.save()

        hello_list = HelloWorld.objects.all()
        return HttpResponseRedirect(reverse("accountapp:hello"))
    else:
        hello_list = HelloWorld.objects.all()
        return render(request, 'accountapp/hello_world.html', context={'hello_list': hello_list})

hello_world.html

...
{% if hello_list %} {% for hello in hello_list %}
  <h4>{{ hello.text }}</h4>
  {% endfor %} {% endif %}
...
profile
https://www.youtube.com/watch?v=whoDs0KRc7k&t=1s

0개의 댓글

관련 채용 정보