본문 바로가기

Python_WEB/Try_Django

[Django]Putting it All Together

CodingEntrepreneurs Django 강의 정리

searches app 추가>

python manage.py startapp searches

 

settings>

"""
Django settings for try_django project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "b#eg47l(0%=d!3uao3xgs68q)_zz+65d4okbfnxsdk-ig$4n9&"

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

ALLOWED_HOSTS = []

LOGIN_URL = "/login"


# Application definition

INSTALLED_APPS = [  # components
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "blog",  # pluggable
    "searches",
]

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 = "try_django.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "templates")
        ],  # 'D:\Code\Study\Try_DJANGO_TUTORIAL_Ver2.2\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",
            ],
        },
    },
]

WSGI_APPLICATION = "try_django.wsgi.application"


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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = "/static/"

LOCAL_STATIC_CDN_PATH = os.path.join(BASE_DIR, "static_cdn_test")

STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, "static")  # live cdn AWS S3
STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles")]

MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, "media")
MEDIA_URL = "/media/"  # django-storages

 

migrate>

python manage.py makemigrations
python manage.py migrate

 

urls>

"""try_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/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.conf import settings
from django.contrib import admin
from django.urls import path, re_path, include  # url
from blog.views import blog_post_create_view

from searches.views import search_view
from .views import home_page, about_page, contact_page, example_page


urlpatterns = [
    path("", home_page),
    path("blog-new/", blog_post_create_view),
    path("blog/", include("blog.urls")),
    path("search/", search_view),
    # re_path(r'^blog/(?P<slug>\w+)/$', blog_post_detail_view),
    path("page/", about_page),
    path("pages/", about_page),
    re_path(r"^pages?/$", about_page),
    re_path(r"^about/$", about_page),
    path("example/", example_page),
    path("contact/", contact_page),
    path("admin/", admin.site.urls),
]

if settings.DEBUG:
    # test mode
    from django.conf.urls.static import static

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

 

admin>

from django.contrib import admin

from .models import SearchQuery

admin.site.register(SearchQuery)

 

models>

from django.conf import settings
from django.db import models


class SearchQuery(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL
    )
    query = models.CharField(max_length=220)
    timestamp = models.DateTimeField(auto_now_add=True)

 

view.html>

{% extends "base.html" %}


{% block content %}

<div class='row'>
    <div class='col-12 col-8 mx-auto'>
        {% if query %}
        <p class='lead'>You searched for {{ query }}</p>
        {% else %}
        <form class="form-inline my-2 my-lg-0" action='/search/'>
            <input class="form-control mr-sm-2" type="search" name='q' placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
        {% endif %}
    </div>
</div>

{% endblock %}

 

views>

from django.shortcuts import render

from .models import SearchQuery


def search_view(request):
    query = request.GET.get("q", None)
    user = None
    if request.user.is_authenticated:
        user = request.user
    if query is not None:
        SearchQuery.objects.create(user=user, query=query)
    context = {"query": query}
    return render(request, "searches/view.html", context)

 

navbar.html>

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="/">Try Django</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="/">Home</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/blog">Blog</a>
            </li>
        </ul>
        <form class="form-inline my-2 my-lg-0" action='/search/'>
            <input class="form-control mr-sm-2" type="search" name='q' placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
    </div>
</nav>

'Python_WEB > Try_Django' 카테고리의 다른 글

[Django]Result  (0) 2020.06.27
[Django]Complex Lookups  (0) 2020.06.27
[Django]Putting it All Together  (0) 2020.06.27
[Django]Image Field and Uploading Images  (0) 2020.06.27
[Django]Static Files and Uploading Files  (0) 2020.06.21
[Django]Published and Draft Posts  (0) 2020.06.21