본문 바로가기

Python_WEB/Try_Django

[Django]A New Database Lookup Value

반응형

CodingEntrepreneurs Django 강의 정리

slug>

짧은 라벨로서, 문자, 숫자, 밑줄 또는 하이픈만을 포함. 일반적으로 URL에 사용

 

urls>

  
"""try_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/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, re_path  # url

from blog.views import blog_post_detail_page
from .views import (
    home_page,
    about_page,
    contact_page,
    example_page,
)

urlpatterns = [
    path("", home_page),
    # path("blog/", blog_post_detail_page),
    path("blog/<str:slug>/", blog_post_detail_page),
    # re_path(r"^blog/(?P<slug>\w+)/$", blog_post_detail_page),
    path("page", about_page),
    path("pages", about_page),
    re_path(r"^pages?/$", about_page),
    re_path(r"^about/$", about_page),
    path("contact/", contact_page),
    path("example/", example_page),
    path("admin/", admin.site.urls),
]

 

views>

from django.http import Http404
from django.shortcuts import render, get_object_or_404

from .models import BlogPost

# Create your views here.


def blog_post_detail_page(request, slug):
    # obj = BlogPost.objects.get(slug=slug)
    # print(post_id.__class__)
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = "blog_post_detail.html"
    context = {"object": obj}  # {'title': objecct.title}

    return render(request, template_name, context)

 

적용 스크린샷>

반응형

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

[Django]A Unique Slug  (0) 2020.06.16
[Django]QuerySet Lookups  (0) 2020.06.16
[Django]get_object_or_404  (0) 2020.06.15
[Django]Handling Dynamic URL Errors  (0) 2020.06.15
[Django]Dynamic URL-based Lookups  (0) 2020.06.15