2월 19, 2024

Django secret key 관리하기

https://www.programmingstory.com/2024/02/django-diary-6-crud-delete.html

지난 포스팅에서 간단한 Diary web을 만들었고 이를 git에 올렸더니 위와 같은 경고 메세지가 떴다. 


즉 내가 만든 github repository가 위험이 있다는 것이다. 즉 원래같으면 

GitGuardian에서 위와 같이 떠야 하는데, At risk가 떴다는 것은 무엇인가를 해결해야 한다는 뜻이다. 

자세히 에러 문구를 보면 위와 같이 open secret incident가 포함되어 있다고 나와있다. 에러 메세지를 더 클릭해보면 settings.py에서 SECRET_KEY가 포함되어 있고 이 secret_key는 비밀 값이기 때문에 프로젝트 코드에 포함되면 안되며, github에도 올리면 안된다. 

 

그래서 우리는 이러한 시크릿 키를 별도의 JSON 파일에 적어서 별도로 관리해주게 된다. 먼저 그럼 우리는 secrets.json 파일을 만들어주도록 하자.

 

secrets.json 파일을 만들고 아래와 같이 코드를 추가해주자.

{
    "SECRET_KEY": "<Django secret key>"
}

 

또는 settings.py에 원래 존재하던 secret_key 코드를 그대로 적어두어도 된다.

 

그리고 이제 settings.py에 들어가서 코드를 아래와 같이 수정해준다.

from pathlib import Path
import os
import json
from django.core.exceptions import ImproperlyConfigured

BASE_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = os.path.dirname(BASE_DIR)
secret_file = os.path.join(BASE_DIR, 'secrets.json') # secrets.json 파일 위치
with open(secret_file) as f:
    secrets = json.loads(f.read())

def get_secret(setting, secrets=secrets):
    try:
        return secrets[setting]
    except KeyError:
        error_msg = "Set the {} environment variable".format(setting)
        raise ImproperlyConfigured(error_msg)

SECRET_KEY = get_secret("SECRET_KEY")

 

그런 다음에 이를 secret key를 git에는 ignore 해주겠다는 뜻으로 .gitignore에 다음과 같이 추가해준다.

# .gitignore
secrets.json

이런식으로 수정해주면 secret key를 별도로 관리할 수 있게 되며, git에서도 secret incident라는 알림이 사라지는 것을 볼 수 있다. 


2월 17, 2024

[Django] diary 만들어보기 (6) CRUD 구현- Delete

https://www.programmingstory.com/2024/02/django-diary-5-crud-update.html

이전 포스팅에서는 CRUD 중 Update하는 법에 대해서 알아보았다. 오늘은 CRUD 중 마지막 delete 하는 법에 대해 알아보도록 하겠다. 

delete를 위해서는 먼저 urls.py에서 delete 부분을 추가해준다.


from django.urls import path
from diary import views

app_name='diary'
urlpatterns = [
    path('', views.index, name='index'),
    path('create/', views.create, name='create'), 
    path('<int:id>/', views.show, name='show'),
    path('<int:id>/edit', views.edit, name='edit'), 
    path('<int:id>/update/', views.update, name='update'), 
    path('<int:id>/delete/', views.delete, name='delete'), # add this line
]

하지만 아직 views.delete가 없으므로 views.py에 delete 함수를 만들어준다.


delete함수는 비교적 간단하다.

def delete(request, id):
    post = Post.objects.get(id=id)
    post.delete() 
    return redirect('diary:index')

post 객체에 대해서 delete()를 호출해주고 다시 index url로 돌아가면 되기 때문이다. 


따라서 별도의 html 파일도 필요하지 않다! 개인적으로 CRUD 중에 가장 간단하지 않나 싶다.


다만 여기서 삭제할 수 있는 버튼을 만들어주어야 하기 때문에 show.html에 삭제 버튼을 넣어준다. 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My diary</title>
  </head>
  <body>
    <div>
      <a href="{% url 'diary:index' %}">return</a>
      <h1>Title: {{ post.title }}</h1>
      <h3>Satisfaction: {{ post.satisfaction }}</h3>
      <p>Content: {{ post.content }}</p>
      <a href="{% url 'diary:edit' id=post.id %}">Edit</a>
      <a href="{% url 'diary:delete' id=post.id %}">Delete</a> 
    </div>
  </body>
</html>

앞의 첫 목록에서도 삭제하고 싶다면 index.html 파일에다 링크를 걸어주면 된다.


<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>My diary</title>
  </head>
  <body>
    <h1>My Diary page<br>
    <a href="/post/create">add</a></h1><br/>
    
    {%for post in posts%}
    <div style="border: 2px solid green;">
      <a href="/post/{{post.id}}">
        <h3> {{post.title}}   </h3>
        <a href="{% url 'diary:delete' id=post.id %}">   Delete</a>
      </a>
      <h3> satisfied: {{post.satisfaction}} </h3>
      <h3> {{post.content}} </h3>
    </div>
    {% endfor %}
  </body>
</html>

이렇게 구현하면 첫 페이지에서도 delete 버튼이 있고 이를 클릭하면 바로 일기가 삭제가 된다. 

 

이 포스팅을 끝으로 일기 만들기를 완료해보았고 CRUD 모든 기능을 구현했다. 다른 CRU가 궁금한 분들은 이전 포스팅을 통해 확인하면 될 것 같다.


2월 17, 2024

[Django] diary 만들어보기 (5) CRUD 구현- Update

https://www.programmingstory.com/2024/02/django-diary-4-crud-read.html

지난 포스팅에 이어 CRUD 중 update를 구현하는 방법에 대해서 알아보도록 하겠다. 


먼저 update를 하기 위해서는 각 일기마다 update를 할 수 있는 버튼을 만들어주도록 하겠다. 

show.html로 가서,

 <a href="{% url 'diary:edit' id=post.id %}">Edit</a>

이 부분을 추가해준다. 즉 전체 코드를 아래와 같이 작성해준다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My diary</title>
  </head>
  <body>
    <div>
      <a href="{% url 'diary:index' %}">return</a>
      <h1>Title: {{ post.title }}</h1>
      <h3>Satisfaction: {{ post.satisfaction }}</h3>
      <p>Content: {{ post.content }}</p>
      <a href="{% url 'diary:edit' id=post.id %}">Edit</a>
    </div>
  </body>
</html>

위에서는 edit url로 가라고 했는데 아직 edit가 없으므로, urls.py에 가서 추가를 해주도록 하겠다.

from django.urls import path
from diary import views

app_name='diary'
urlpatterns = [
    path('', views.index, name='index'),
    path('create/', views.create, name='create'), 
    path('<int:id>/', views.show, name='show'),
    path('<int:id>/edit', views.edit, name='edit'), #add this line
    path('<int:id>/update/', views.update, name='update'), # add this line
]

수정을 하는 것은 사실 수정을 하고 그것을 update를 하고, 두 가지가 동시에 필요하기 때문에 두 가지 url을 만들어주었고 각각이 views.edit과 views.update를 부르고 있으니 views.py에 두 함수를 만들어주도록 하자

 

def edit(request, id):
    post = Post.objects.get(id=id)
    return render(request, 'diary/edit.html', {'post':post})

def update(request, id):
    title =request.POST.get('title')
    content =request.POST.get('content')
    satisfaction=request.POST.get('satisfaction')
    Post.objects.filter(id=id).update(title=title, satisfaction=satisfaction, content=content)
    return redirect(f'/post/{id}/')

edit은 단순히 객체를 받아와서 edit.html 페이지로 render하면 되는 것이고 update는 request의 POST에서 업데이트할 title, content, satisfaction을 가져와서 이를 udpate해주는 것이다. 그런 다음에 다시 해당 일기 내용을 보여주는 링크로 redirect 시켜준다. 


이제 마지막으로 templates에서 edit.html만 만들어주면 된다. update 하는 과정에서는 html을 render하지 않으므로 update.html은 필요 없다. 

templates/diary/에 edit.html을 생성해준다.

<body>
    <h1>Edit diary</h1>
    <form action="/post/{{ post.id }}/update/", method="POST">
        {% csrf_token %}
        <h3>title</h3>
        <input type="text" name="title" value="{{ post.title }}" />
        <p>satisfaction</p>
        <input type="text" name="satisfaction" value="{{ post.satisfaction }}" />
        <p>content</p>
        <textarea type="text" name="content" rows="30" cols="40">{{ post.content }}</textarea><br/>
        <input type="submit" value="submit"/>
    </form>
</body>

이런식으로 써주고

 

python manage.py runserver

를 해보면 수정이 아주 잘 되는 것을 알 수 있다.

 

다음 포스팅에서는 CRUD 중 마지막 Delete하는 법에 대해서 알아보도록 하겠다. 


2월 17, 2024

[Django] diary 만들어보기 (4) CRUD 구현-Read

https://www.programmingstory.com/2024/02/django-diary-3-crud-create.html

포스팅이 계속해서 이어지고 있다. 저번 포스팅에서는 CRUD 중에서 Create를 알아보았고 이번에는 CRUD 중에서 Read를 알아보려고 한다. 


Read를 하는 과정을 생각해보면, 

먼저 일기를 클릭하면 post/일기아이디/ url로 이동하여서 일기 페이지를 보여주어야 할 것이다. 그러기 위해서 먼저 urls.py부터 추가를 해보자. 


from django.urls import path
from diary import views

app_name='diary'
urlpatterns = [
    path('', views.index, name='index'),
    path('create/', views.create, name='create'), 
    path('<int:id>/', views.show, name='show'), # add this line
]


하지만 여기까지 썼다면 당연히 에러가 날 것이다. 왜냐하면 우리는 아직 views.show 함수를 만들지 않았기 때문이다. 그러면 이제 views.show를 만들러 views.py에 가보자

 

show 함수는 해당 아이디에 해당되는 일기를 보여주어야 하기 때문에 parameter로 추가적으로 id 값을 함께 가지게 된다.


def show(request, id):
    post = Post.objects.get(id=id)
    return render(request, 'diary/show.html', {'post':post})


이러면 show 함수는 diary/show.html로 render된다는 것을 알 수 있다. 그러면 순서대로 따라가, 우리는 show.html을 다시 만들어주어야 한다. 하던대로 이를 templates/diary/폴더 안에다가 생성해준다. 

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My diary</title>
  </head>
  <body>
    <div>
      <a href="{% url 'diary:index' %}">return</a>
      <h1>Title: {{ post.title }}</h1>
      <h3>Satisfaction: {{ post.satisfaction }}</h3>
      <p>Content: {{ post.content }}</p>
    </div>
  </body>
</html>


가장 위에는 홈 화면으로 돌아갈 수 있게 index url로 연결시켜줄 수 있는 return 버튼을 만들어주었고 그 다음에는 받은 post 객체에 대해 title, satisfaction, content 정보를 각각 출력할 수 있도록 코드를 작성했다. 

 

이런 식으로 한다면 

Title을 클릭하면 


이런식으로 Title, satisfaction, content가 보이는 페이지로 이동하고 위의 return을 누르면 다시 메인 화면으로 돌아오게 된다. 

 

다음 포스팅에서는 CRUD의 update를 다루어보도록 하겠다.


2월 17, 2024

[Django] diary 만들어보기 (3) CRUD 구현-Create

https://www.programmingstory.com/2024/02/django-diary-2-mtv-models-templates-view.html

전 포스팅에서는 MTV 패턴의 기본적인 골격을 잡아보는 연습을 했다. 이제는 diary에서 새로운 일기를 추가하고, 수정하고, 삭제하고 보여주는 것을 구현해볼 것이다. 

흔히 우리는 이것을 CRUD라고 하는데 (Create, Read, Update, Delete)의 약자이다. 


먼저 Create 부터 구현을 해보자.

Create을 하기 위해서는 post/create/라는 url로 이동하면 새로운 화면이 보여야 하고, 그러기 위해서는 urls.py 함수에 views.create으로 이동할 수 있게 views 함수도 수정을 해주어야 한다. 

 

먼저 그럼 diary/urls.py에 들어가서 url 경로부터 추가를 해주자. 

from django.urls import path
from diary import views

urlpatterns = [
    path('', views.index, name='index'), 
    path('create/', views.create, name='create'), # add this line
]


그리고 urlpatterns에도 써있듯이, 두 번째 인자로 views.create라는 함수를 필요로 함으로 views.py에 가서 create 함수를 만들어주자. 아래의 코드처럼 작성해주면 된다. 

#views.py
def create(request):
    return render(request, 'diary/create.html')

 

create 함수는 create.html 페이지로 render해주기 때문에 create.html 페이지를 새롭게 만들 필요가 있다. 미리 만들어놓은 templates/diary 폴더에 create.html 파일을 하나 만들어주고 새 일기를 추가할 때 화면을 작성해주면 된다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My diary</title>
  </head>
  <body>
    <h1>new diary</h1>
    <form action="{% url 'diary:index' %}" method="POST">
      {% csrf_token %}
      <p>title</p>
      <input name="title" /> <br />
      <p>Satisfaction</p>
      <input name="satisfaction" /> <br />
      <p>content</p>
      <textarea name="content" rows="30" cols="40"></textarea> <br />
      <input type="submit" value="submit" />
    </form>
  </body>
</html>

create.html에서 create한 정보를 다시 diary의 index url로 넘겨주는 것이고 그 방식이 POST가 되는 것이다. 새롭게 추가할 경우에 필드 값인 title, satisfaction, content 값을 input으로 받을 수 있도록 해 주었다. 

 

그러면 이제 index 함수에서 들어오는 method가 POST이냐 GET이냐에 따라서 상황을 다르게 처리해주어야 한다. 

그러므로, views.py에서 def index를 아래와 같이 수정해준다.

def index(request):
    if request.method == 'GET': # index
        posts = Post.objects.all()
        return render(request, 'diary/index.html', {'posts': posts})
    elif request.method == 'POST': # create
        title = request.POST['title']
        satisfaction = request.POST['satisfaction']
        content = request.POST['content']
        Post.objects.create(title=title, satisfaction=satisfaction, content=content)
        return redirect('diary:index') 

즉, 그냥 목록을 보여줄 때와 새롭게 create을 통해 POST할 경우를 분리하는 것이다. 

 

또한, 

Create을 하기 위해서는 추가를 할 수 있는 버튼이 필요하다. 버튼을 누르면 새로운 일기를 추가할 수 있는 페이지로 넘어가야 하기 때문에 index.html에 아래와 같이 수정을 해준다. 

<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>My diary</title>
  </head>
  <body>
    <h1>Diary page</h1>
    <a href="/post/create">add</a>
    {%for post in posts%}
    <div style="border: 2px solid green;">
      <a href="/post/{{post.id}}">
        <h3> {{post.title}} </h3>
      </a>
      <h3> satisfied: {{post.satisfaction}} </h3>
      <h3> {{post.content}} </h3>
    </div>
    {% endfor %}
  </body>
</html>

<body> 뒤에 add 라는 링크를 걸어 준 것 이외에는 전 포스팅에서 다루었던 코드와 동일하다. 

 

이렇게 해주고 확인해보면,

이런 식으로 add 버튼이 새롭게 생겼고, add를 클릭해보면


위와 같이 화면이 잘 나오는 것을 알 수 있다. 이렇게 하면 새 일기를 만들어 줄 수 있다.

 

이제 CRUD 중에서 C를 구현했으니 다음 포스팅에서는 R (read)에 대해서 알아보도록 하겠다. 


2월 17, 2024

[Django] diary 만들어보기 (2) MTV 패턴 이란? models, templates, view 설정

https://www.programmingstory.com/2024/02/django-diary.html

우선 전 포스팅처럼 기본 설정을 한 뒤에 이어서 시작해보겠다. 


먼저 사용자에게 보여줄 화면을 만들어주어야 한다. 사용자에게 보여줄 화면은 template이 담당하고 있고 특히나 중요한 것은 django에서는 무조건 html 파일을 templates 라는 폴더 안에서 찾기 때문에 templates라는 폴더를 하나 만들어주자. 그리고 전 포스팅에서도 언급했듯이, django에서는 여러 개의 앱을 같이 만들 수 있기 때문에 diary 폴더의 templates 안에 diary라는 이름의 폴더를 하나 더 만들어주자. 그리고 그 폴더 안에 index.html 파일을 하나 만들어주자. 그런 다음에 index.html 파일 안에 간단히 적어보자

 

우선은 화면만 구상을 할 것이므로 간단하게만 아무거나 적어도 관계없다.

<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>My diary</title>
  </head>
  <body>
    <h1>Diary page</h1>
  </body>
</html>

우선 위와 같이 title과 h1 정도만 적어주었다. 


그런 다음 terminal에 


python manage.py runserver


를 적어보자. 위 명령어는 실제로 화면이 어떻게 나오는지를 살펴보기 위해 runserver를 해보겠다는 뜻이다. 

 

그러면 


위와 같이 나올 텐데 위 그림에서 

 

빨간색으로 표시된 부분에 control을 누른 상태에서 클릭을 하면 인터넷 상에서 다음과 같은 창이 뜨는 것을 알 수 있을 것이다. 

우리가 html 페이지를 작성했지만 아직 아무것도 나오지 않는 것을 알 수 있다. html 페이지가 보이기 위해서는 html 페이지를 보여달라고 요청하는 views.py가 필요하다.

 

따라서 diary/views.py에 들어가서 아래와 같이 index 함수를 작성해보자.


from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, 'diary/index.html')

 

다음으로 url 부분을 작성해주어야 한다. diary_project/urls.py에 들어가서 아래와 같이 코드를 수정해주자.


from django.contrib import admin
from django.urls import path
import diary.views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', diary.views.index, name='index')
]


즉 diary.views를 import 해주고 path를 하나 더 추가해준것이다. ' ' 라는 것은 기본 경로 (localhost:8000/) 로 url이 들어올 시에 두 번째 인자로 들어온 함수를 실행시켜주겠다는 것이다. 즉 만약 localhost:8000/ 로 들어오면 diary.views.index 함수를 실행시켜주는 것이고 diary.views.index 함수는 index.html 페이지를 render하고 있으니 index.html 페이지가 보이게 되는 것이다. 

 

이렇게 하고 terminal에 python manage.py runserver를 입력하면,


 이런식으로 html 페이지가 잘 나온 것을 알 수 있다.


다음 다시 diary_project의 urls.py 에 들어가서 urlpatterns에 하나를 더 추가해주도록 하겠다.


from django.contrib import admin
from django.urls import path
import diary.views
from django.conf.urls import include # 새로 추가
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', diary.views.index, name='index'),
    path('post/', include('diary.urls')), #새로 추가
]


이렇게 되면 localhost:8000/post/로 들어오는 것들은 diary.urls에서 처리해주겠다라는 말이 된다. 이렇게 코드를 작성해주면 diary/urls가 없기 때문에 에러가 나게 될 것이다.

따라서 diary 폴더 안에 urls.py를 새로 하나 만들어 주고 아래와 같이 코드를 적어준다.


from django.urls import path
from diary import views

urlpatterns = [
    path('', views.index, name='index'), # 'localhost:8000/post/'
]


post/로 들어왔을 때도 views.index를 보여주겠다라는 것이므로 views.index함수를 두 번째 인자로 적어준다. 


다음으로는 model을 작성해주어야 한다. 

diary에 models.py 파일에 아래와 같이 코드를 작성해주자. 각각의 필드는 다른 것을 사용해도 된다. 나는 diary에 필요한 필드로 우선 제목, 내용, 그리고 만족도를 넣어주었고 title과 만족도는 굳이 길지 않아도 되니, max_length를 지정해주고 CharField 타입으로 정해주었다. 


from django.db import models
from django.utils import timezone

# Create your models here.
class Post(models.Model): 
 
    title = models.CharField(max_length=256)
    content = models.TextField()
    satisfaction= models.CharField(max_length=1)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(blank=True, null=True)

    def update_date(self): 
        self.updated_at = timezone.now()
        self.save()

    def __str__(self):
        return self.title


여기서 id는 자동으로 추가해주기 때문에 굳이 field로 명시해줄 필요가 없다. 

 

그리고 이렇게 모델이 바뀌었다면 우리는 꼭 migration을 시켜주어야 한다. 

python manage.py makemigrations
python manage.py migrate

위 두 줄을 각각 terminal에 입력하여 migration을 시켜주자. 

 


이제 모델이 바뀌었으니 다시 view.py와 index.html을 바꾸어주어야 한다. view.py에서는 각각의 post 객체를 모두 다 index.html로 넘겨주도록 하겠다. 

 

그래서 우선 객체를 받아서 이를 넘겨주는 식으로 아래와 같이 view.py를 수정해주었다.

from django.shortcuts import render
from .models import Post

# Create your views here.
def index(request):
    posts=Post.objects.all()
    return render(request, 'diary/index.html', {'posts': posts})


그 다음에 template에 있는 index.html도 받은 post 객체를 화면에 띄울 수 있도록 수정해준다. 

 

index.html 파일을 아래와 같이 수정해준다.

<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>My diary</title>
  </head>
  <body>
    <h1>Diary page</h1>
    {%for post in posts%}
    <div style="border: 2px solid green;">
      <a href="/post/{{post.id}}">
        <h3> {{post.title}} </h3>
      </a>
      <h3> satisfied: {{post.satisfaction}} </h3>
      <h3> {{post.content}} </h3>
    </div>
    {% endfor %}
  </body>
</html>

 

이렇게 하면 posts라는 모든 객체 중에 for문을 돌면서 하나의 객체 post에 대해 title, satisfaction, content를 출력해준다. 


이렇게 해서 models, view, urls, templates 의 관계를 알아보았다. 이를 우리는 django에서 MTV 패턴이라고 한다. MTV 패턴은 Model, Template, View의 약자로 이 세 가지가 연계되는 패턴을 의미한다. 위의 설명을 잘 따라갔다면 이것이 무엇을 의미하는지 이해할 수 있을 것이다.

 

Model은 데이터를 저장하는 형태를 설정하고, Template 안에 있는 html 파일에서 유저에게 보여줄 화면을 설정하고, View에서 데이터를 처리하여 html 파일과 연결시켜준다. 

 

이러한 django의 MTV 패턴을 잘 익혀두면 전반적인 큰 그림을 이해하기 쉽기 때문에 오래 걸리더라도 이해해보자. 

 


 여기까지 하면 django의 MTV 패턴을 이해할 수 있지만 새로운 posting을 추가하거나, 삭제하거나, 수정할 수 없다. 다음 포스팅에서는 diary의 추가적인 기능을 구현해보도록 하겠다.


2월 17, 2024

[Django] diary 만들어보기-기본 설정

django를 사용해서 간단한 일기웹을 만들어보는 프로젝트를 해보겠다. 


먼저 가상 환경부터 만들어주자. 

터미널에 

python -m venv .venv
source .venv/Scripts/activate

라고 타이핑 쳐서 가상환경을 실행시켜준다. 

 

그러면 터미널의 앞에 (.venv) 라고 나와있는 것을 볼 수 있을 것이다. 

 

그런 다음에 가장 먼저 django를 설치해 주어야 할 것이다. 

 

pip install django

라고 입력하여서 django를 설치해준다. 물론 앞에는 (.venv)가 붙어 있는 상태일 것이다. 


위와 같은 warning이 떠도 이것은 버전이 최신 버전이 아니라는 뜻이므로 크게 신경 쓸 것이 없다. 위에 successfully installed 라는 문구가 보이면 성공이다. 

 


다음으로 프로젝트를 생성해주자.

$ django-admin startproject diary_project .

위와 같이 입력해주면 현재 위치에 diary_project라는 이름으로 프로젝트를 만들어주겠다는 뜻이다. 

 

그런 다음에 왼쪽에 나와있는 구조를 살펴보게 되면,



위와 같이 우리가 만들어주지 않았는데도 manage.py 파일이나, urls.py/settings.py 등의 파일이 자동으로 생성된 것을 알 수 있다. 


다음으로 django 앱을 만들어보자. 하나의 프로젝트 안에는 여러 앱을 만들 수 있기 때문에 앱을 따로 생성해주어야 한다. 우리는 일기 관련 앱을 만들 것이기 때문에 'diary'라는 이름의 앱을 만들어주자.

 

(.venv) django-admin startapp diary 

 

라고 입력해준다. 여기서 앞에 붙는 (.venv)는 우리가 타이핑 치는 것이 아니라 자동으로 생성되는 것이다. 



그러면 이제 위와 같이 diary라는 폴더가 하나 만들어진 것이 보일 것이다. 그런 다음에 우리가 이 앱을 사용하겠다고 알려주기 위해서 diary_project 안에 있는 settings.py에 들어가서 installed_app 부분에 diary를 추가해주자

 

즉 아래와 같이 코드를 적어주면 된다.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'diary',  #추가해주자
    'sass_processor', #추가해주자 이 설명은 아래부분에
]

그 다음 다시 위 settings.py 에서 'sass_processor'를 추가해주었는데 추가적으로 코드를 적어줄 부분이 있다. 

다시 diary_project.settings.py에 가서 가장 윗부분에 

import os 

를 추가해주고, 

installed_apps 아래부분에 

SASS_PROCESSOR_ENABLED =  True
SASS_PROCESSOR_ROOT =  os.path.join(BASE_DIR, 'diary', 'static')

라고 적어주자. 즉 settings.py 부분 코드를 보면 아래와 같을 것이다.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sass_processor',
    'diary', 
]
SASS_PROCESSOR_ENABLED =  True
SASS_PROCESSOR_ROOT =  os.path.join(BASE_DIR, 'diary', 'static')

다음으로 필요한 패키지 설치를 위해 터미널에 아래와 같이 적어준다.

 

pip install libsass django-compressor django-sass-processor

이렇게 설정을 마쳤다면 기본적으로 설정은 다 마친 상태이다. 이제 다음 포스팅부터 본격적으로 일기 웹을 만들어보도록 하자. 


2월 10, 2024

[django] no such table 에러 해결법

django에서 python manage.py runserver를 한 뒤에 결과를 확인해보면 가끔 no such table 에러가 뜨는 경우가 있다. 

migrate가 문제인가 하여 

python manage.py makemigrations
python manage.py migrate

를 둘 다 해봐도 똑같은 에러가 떴다.


매번 해당 에러에 대해서 해결되었던 방법은 migrate할 때 아래와 같은 코드로 실행하는 것이다.

python manage.py migrate --run-syncdb

syncdb라는 것은 settings.py의 Installed apps에서 추가된 앱에 대한 테이블을 처음 db에 만들어주는 command라고 생각할 수 있다. 

 

에러의 메세지가 말하는 것처럼 DB에 해당 table이 없기 때문에 생기는 에러기 때문에 mirgate를 할 때 위 command처럼 --run-syncdb를 붙여서 실행해준 다음 다시 

python manage.py runserver

를 해주면 에러가 해결되는 것을 알 수 있다.