[TIL | 240103] Django - 관리자, 템플릿, URL별칭

sun_U·2024년 1월 4일
0

TIL

목록 보기
10/21
post-thumbnail

장고 관리자


  1. Super User 생성
    • python [manage.py](http://manage.py) createsuperuser

  1. 장고 관리자 화면

  1. 모델 관리
    • Question 모델을 관리자에 등록 pybo/admin.py
      from django.contrib import admin
      from .models import Question
      
      # Register your models here.
      admin.site.register(Question)

    - 관리자 화면에서 Question 모델 질문 생성, 조회, 수정, 삭제 가능
    

  1. 모델 검색

    • 관리자 화면에서 subject로 질문 데이터 검색하기

    admin.py (수정)

    from django.contrib import admin
    from .models import Question
    
    # Register your models here.
    class QuestionAdmin(admin.ModelAdmin):
        search_fields = ['subject']
    
    admin.site.register(Question, QuestionAdmin)

조회와 템플릿


질문 목록과 질문 상세 기능 구현

1. 질문 목록

  • 메인 페이지 수정 views.py
    from django.shortcuts import render
    from .models import Question
    #from django.http import HttpResponse 
    
    # Create your views here.
    def index(request):
        question_list = Question.objects.order_by('-create_date') #order_by : 조회 결과 정렬, - : 역방향 정렬
        context = {'question_list': question_list}
        return render(request, 'pybo/question_list.html', context) #render: 파이썬 데이터를 템플릿에 적용하여 HTML로 반환
    • 템플릿 파일 - HTML파일과 비슷하지만 파이썬 데이터를 읽어서 사용할 수 있는 HTML 파일

템플릿 디렉터리

  • render 에서 사용한 pybo/question_list.html 파일 작성 전, 템플릿 저장 디렉터리 설정

settings.py

(... 생략 ...)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'], # 추가
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
(... 생략 ...)
  • 디렉터리 생성 mkdir templates
    • 하나의 웹에서 여러 개의 앱을 사용할 수도 있을므로 경로를projects/mysite/pybo/templates이 아닌 /projects/mysite/templates/pybo 디렉터리를 사용

    • 공용 템플릿 - projects/mysite/templates

      django_prac1/templates/pybo/question_list.html

      {% if question_list %}
          <ul>
          {% for question in question_list %}
              <li><a href="/pybo/{{ question.id }}/">{{ question.subject }}</a></li>
          {% endfor %}
          </ul>
      {% else %}
          <p>질문이 없습니다.</p>
      {% endif %}

템플릿 태그

1. 분기

{% if 조건문1 %}
    <p>조건문1에 해당되는 경우</p>
{% elif 조건문2 %}
    <p>조건문2에 해당되는 경우</p>
{% else %}
    <p>조건문1, 2에 모두 해당되지 않는 경우</p>
{% endif %}

2. 반복

{% for item in list %}
    <p>순서: {{ forloop.counter }} </p>
    <p>{{ item }}</p>
{% endfor %}

3. 객체 출력

# 객체 출력
{{ 객체 }}
# 객체 속성 출력 
{{ 객체.속성 }}

2. 질문 상세

pybo/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index),
    path('<int:question_id>/', views.detail),
]

pybo/views.py

# detail 함수 추가
def detail(request, question_id):
    question = Question.objects.get(id=question_id)
    context = {'question': question}
    return render(request, 'pybo/question_detail.html', context)

question_detail.html

<h1>{{ question.subject }}</h1>
<div>
    {{question.content}}
</div>

3. 오류 페이지

  • 존재하지 않는 데이터 요청시 500 에러 발생 → 404 에러 페이지를 리턴하는 것이 좋음 views.py
    from django.shortcuts import render, get_object_or_404
    from .models import Question
    #from django.http import HttpResponse 
    
    # Create your views here.
    def index(request):
        question_list = Question.objects.order_by('-create_date')
        context = {'question_list': question_list}
        return render(request, 'pybo/question_list.html', context)
    
    def detail(request, question_id):
        question = get_object_or_404(Question, pk = question_id)
        context = {'question': question}
        return render(request, 'pybo/question_detail.html', context)

  • 200 - 성공
  • 500 - Internal Server Error
  • 404 - Resource Not Found Error

URL 별칭


1. URL 하드코딩

question_list.html

<li><a href="/pybo/{{ question.id }}/">{{ question.subject }}</a></li>

→ url 리팩토링이 빈번해 구조 변경이 일일이 템플릿을 찾아가 수정해야 함

→ 따라서 실제 링크 대신 링크 주소가 매핑되어 있는 별칭 사용하기

2. URL 별칭

URL 매핑에 name 속성 부여

pybo/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

question_list.html

{% if question_list %}
    <ul>
    {% for question in question_list %}
        <li><a href="{% url 'detail' question.id %}">{{ question.subject }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>질문이 없습니다.</p>
{% endif %}

3. URL 네임 스페이스

  • 하나의 프로젝트에 여러 앱을 사용할 때 동일한 URL별칭이 생길 수 있으므로 app_name 변수 지정

pybo/urls.py

from django.urls import path

from . import views

app_name = 'pybo'

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

question_list.html

  • {% url 'pybo:detail' question.id %}
profile
Data Engineer AI/ Metaverse :)

0개의 댓글