본문 바로가기
개발일지/Django

Django - 필터처리

by 개발에정착하고싶다 2022. 9. 30.

음.. 내생각에 django는 초보로써 숙련이 되는수준도 되지 않으면 사실상

구글링이 아무짝에도 쓸모없다고 생각한다.

이유는 django의 구동원리가 여기저기 연동되어서 작동되기 때문이다.

즉, 그 중 한개만 잘못되더라도 작동이 되지 않으며,

에러메세지의 대부분은 내가 직접 작성을 했으면 그래도 뭘 고쳐야할지 감이 오는데,

그게 아니라면 뭘 고쳐야 할지도 찾기가 어려울것이다.

특히나 파이썬을 고급문법인 클래스 까지 마치지 않은 사람에 대해선 말이다.

따라서, 혹시 파이썬 기반없이 구글링으로 django를 배우려는 사람은 제발 파이썬 기반부터

닦고 학습을 하든 구글링을 하든 해줬음 하는 바램이다..

나의 경우는 파이썬을 전체적으로 클래스 상속, 클래스 사용을 제외하곤 모두 이해하는 수준이 되는데 까지 6개월정도 걸린것같다.

순수 파이썬만 공부한 시간은 아니고 순수하게는 3~4개월걸린것같다.

 

음.. django를 설명할 수준이 되기까지는

그냥 '이런 코드로 작동을 했더라' 정도로 정리하려고 한다.


# 첫번째 파일

my_site > my_app > urls.py

 

from django.urls import path
from . import views

urlpatterns = [
    path('', views.example_view),
    path('variable/', views.variable_view)
]

이 부분을 작성할때는 urlpatterns에서 s를 빼먹었다고 작동이 안되기도 했고,

에러메세지를 보고 고쳤다.


# 두번째 파일

my_site > my_app > templates > my_app > variable.html

 

<html lang='en'>
<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>Document</title>
</head>
<body>
    <h1>VARIABLE.HTML</h1>
    <h2>Her first name was {{first_name | lower | capfirst}} and her last was {{last_name | capfirst}}</h2>
    {% comment %} 리스트의 0번째 리스트를 가져오는 의미다. {% endcomment %}
    <h2>{{some_dict}}</h2>
    {% comment %} 장고의 주석처리 방법 {% endcomment %}
    <h2>{# this is a comment # }</h2>
</body>
</html>

{% comment %}  {% endcomment %}
<!--  -->

# 세번째 파일

my_site > my_site > urls.py

 

"""my_site URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    # my_app 폴더 내부의 urls.py 파일을 가져오는것
    # path는 정확한 경로가 아니여도 된다. 이름이 일치하면 가져오는 것 같다.
    path('my_app/', include('my_app.urls')),    
]

# 네번째 파일

my_site > my_app > views.py

from django.shortcuts import render

# Create your views here.

def example_view(request):
    # my_app/templates/my_app/example.html
    return render(request, 'my_app/example.html')

def variable_view(request):

    

    my_var = {
        'first_name': 'Rosalind',
        'last_name': 'Frankiln',
        'some_list':[1,2,3],
        'some_dict':{'inside_key':'inside_value'}
    }
    
    return render(request, 'my_app/variable.html', context=my_var)

# 다섯번째 파일

my_site > my_site > settings.py

"""
Django settings for my_site project.

Generated by 'django-admin startproject' using Django 4.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-h$2)0u79!_n66h8rbo)_@)_g-6&tv4xyy5q8*oc74-9je1jygo"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'my_app.apps.MyAppConfig',
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "my_site.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "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",
            ],
        },
    },
]

WSGI_APPLICATION = "my_site.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",},
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# 여섯번째 파일

my_site > my_app > templates > my_app > example.html

<html lang='en'>
<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">
</head>
<body>
    <h1>example html template connected</h1>
</body>
</html>

# 일곱번째 파일

my_site > my_app > apps.py

from django.apps import AppConfig


class MyAppConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "my_app"

 

-끗