사이트맵은 사용자나 소프트웨어를 통해 접근이 가능하다. 수많은 사이트들은 체계적인 뷰, 일반적으로 사이트의 계층적인 뷰를 표출하기 위해 사용자가 볼 수 있는 사이트맵을 보유하고 있다. 방문자가 특정 문서를 찾는데 도움을 주고 웹 크롤러에 의해 사용될 수도 있다.

검색 엔진과 기타 크롤러가 사용하는 경우 사이트 내 문서를 나열하는 XML 사이트맵이라는 구조화된 포맷이 있어서 상대적 중됴오와 업데이트 주기를 알 수 있다. 이는 robots.txt 파일로부터 지시되며 보통 sitemap.xml이라는 이름을 가진다.

한 번에 사이트 개요 내용을 볼 수 있도록 둘러보기 도움을 제공하는 역할을 하기도 한다.

 

https://ko.wikipedia.org/wiki/%EC%82%AC%EC%9D%B4%ED%8A%B8%EB%A7%B5

 

사이트맵 - 위키백과, 우리 모두의 백과사전

구글이 정의한 XML 사이트맵 파일 프로토콜에 대해서는 사이트맵스 문서를 참고하십시오. 사이트맵(sitemap) 또는 사이트 맵(site map)은 도메인 내의 웹사이트의 페이지 목록이다. 사이트 맵에는 3가

ko.wikipedia.org

 

1. Settings/base.py

INSTALLED_APPS = [
	...
	'wagtail.contrib.sitemaps',
    	...
    	'django.contrib.sitemaps'
]

 

 

2. myproject/urls.py

...
from wagtail.contrib.sitemaps.views import sitemap
...


urlpatterns = [
	...
    path('sitemap.xml', sitemap),

]

http://127.0.0.1:8000/sitemaps.xml

 

 

 

 

3. models.py

class BlogListingPage(RoutablePageMixin, Page):
    
    template = "blog/blog_listing_page.html"
    
    custom_title = models.CharField(
        max_length=100, 
        blank=False,
        null=False,
        help_text="Overwrites the default title",
        )
    
    content_panels = Page.content_panels + [
        FieldPanel("custom_title"),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['posts'] = BlogDetailPage.objects.live().public()         
        return context
    
    @route(r'^latest/$')
    def latest_blog_posts(self, request, *args, **kwargs):
        context = self.get_context(request, *args, **kwargs)
        context["posts"] = context["posts"][:1]
        return render(request, "blog/latest_posts.html", context)
    
    def get_sitemap_urls(self, request):
        # 사이트 맵을 사용하고 싶지 않을때는 return [] 을 해주면 된다.
        
        sitemap = super().get_sitemap_urls(request)
        sitemap.append(
            {
                "location": self.full_url + self.reverse_subpage("latest_blog_posts"),
                "lastmod": (self.last_published_at or self.latest_revision_created_at),
                "priority": 0.9,
            }
        )
        
        return sitemap

get_sitemap_urls 함수를 확인하면 된다. 일반적으로 Publish된 Page 모델들은 Sitemap이 잘 나타나지만 latest_blog_posts처럼 templates으로 render할 경우 Sitemap에 표시되지 않는다. 그럴경우 get_sitemap_urls로 직접 정의 해주면 된다. 

'Back-End > Wagtail, Django' 카테고리의 다른 글

Wagtail, Django Paginator  (0) 2021.11.21
Wagtail StructValue  (0) 2021.11.18
Wagtail 참고 사이트  (0) 2021.11.17
Wagtail git ignore setting  (0) 2021.11.16
Wagtail Routable Pages  (0) 2021.11.16

1. 공식 문서 사이트 : https://docs.wagtail.io/en/stable/

2. Awesome Wagtail : https://github.com/springload/awesome-wagta

3. awesomeonpensource : https://awesomeopensource.com/projects/wagtail

4. neon jungle : https://github.com/neon-jungle

5. django : https://github.com/django/django/tree/main

6. wagtail : https://github.com/wagtail/wagtail

7. 장고 공식 문서 사이트 : https://www.djangoproject.com/

8. Accord Box : https://www.accordbox.com/blog/wagtail-tutorials/

9. learn wagtail : https://learnwagtail.com/

-> https://github.com/CodingForEverybody/learn-wagtail

-> https://www.youtube.com/c/CodingForEverybody

10. bakerydemo : https://github.com/wagtail/bakerydemo

11. consumerfinance : https://cfpb.github.io/consumerfinance.gov/

12. third-party tutorials : https://docs.wagtail.io/en/stable/advanced_topics/third_party_tutorials.html#third-party-tutorials

'Back-End > Wagtail, Django' 카테고리의 다른 글

Wagtail StructValue  (0) 2021.11.18
Wagtail Sitemap  (0) 2021.11.17
Wagtail git ignore setting  (0) 2021.11.16
Wagtail Routable Pages  (0) 2021.11.16
Wagtail BaseSetting  (0) 2021.11.15

.gitignore

__pycache__/
0*.py
!home/migrations/0001*
!home/migrations/0002*
media/

Wagtail로 프로젝트를 진행할 때, gitignore에 기본적으로 추가해주면 된다.

 

 

'Back-End > Wagtail, Django' 카테고리의 다른 글

Wagtail Sitemap  (0) 2021.11.17
Wagtail 참고 사이트  (0) 2021.11.17
Wagtail Routable Pages  (0) 2021.11.16
Wagtail BaseSetting  (0) 2021.11.15
Wagtail Debug Toolbar(+ Django)  (0) 2021.11.13

https://www.youtube.com/watch?v=W2oHKiAYl3U&list=PLMQHMcNi6ocsS8Bfnuy_IDgJ4bHRRrvub&index=17 

 

Wagtail Routable Pages를 공부하면서 정리해보려고 한다. 

 

그동안 프로젝트를 진행하면서 Ajax 사용으로 많이 사용했었는데 정확한 사용방법을 숙지하지 못했던 것 같아서 정리하고 넘어가려고 한다. 

 

1. Settings

 

settings/base.py

INSTALLED_APPS = [
	'wagtail.contrib.routable_page',
]

 

 

 

2. Models

 

blog/models.py

from django.shortcuts import render
...
from wagtail.contrib.routable_page.models import RoutablePageMixin, route


class BlogListingPage(RoutablePageMixin, Page):
    
    template = "blog/blog_listing_page.html"
    
    custom_title = models.CharField(
        max_length=100, 
        blank=False,
        null=False,
        help_text="Overwrites the default title",
        )
    
    content_panels = Page.content_panels + [
        FieldPanel("custom_title"),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['posts'] = BlogDetailPage.objects.live().public()         
        return context
    
    @route(r'^latest/$')
    def latest_blog_posts(self, request, *args, **kwargs):
        context = self.get_context(request, *args, **kwargs)
        context["posts"] = context["posts"][:1]
        return render(request, "blog/latest_posts.html", context)

동영상대로 BlogListPage에 추가했다. 여기서 중요한 점은 RoutablePageMixin을 Page앞에 적어줘야 한다는 점이다. 

(RoutablePageMixin, Page)

 

route를 사용하기 위해 데코레이터를 사용하는데 

@route(r'^$')형태로 사용한다. ^와$ 사이에 이동할 url 주소를 적어주면 된다.

(/는 Wagtail과 Django url 설정의 기본이다. 다만 ?를 사용할 경우 생략해도 되는데 ?가 자동으로 /를 추가해주기 때문이다. @route(r'^latest?$'))

 

route에서 get_context을 overwrite할 수가 있다. get_context에서는 현재 발행 중인 모든 blog post를 posts에 저장하여 return 해주었고 route에서는 context를 overwrite해서 가장 최근에 등록된 blog post 1개를 보여주는 것이다. 

 

그리고 blog/latest_posts.html에 request와 context를 같이 render 해준다.

 

 

3. Templates

 

2개의 template를 살펴볼 것이다. 한개는 blog_listing_page.html 다른 하나는 latest_posts.html이다. 

 

1)

blog/blog_listing_page.html

{% extends "base.html" %}

{% load wagtailimages_tags wagtailroutablepage_tags %}

{% block content %}

    <a href="{% routablepageurl page 'latest_blog_posts' %}">View Latest Posts Only</a>

    <div class="container">
        {% for post in posts %}
            <div class="row">
                <div class="col-sm-3">
                    {% image post.blog_image fill-250x250 as blog_img %}
                    <a href="{{ post.url }}">
                        <img src="{{ blog_img.url }}" alt="{{ blog_img.alt }}">
                    </a>
                </div>
                <div class="col-sm-9">
                    <a href="{{ post.url }}">
                        {{ post.custom_title }}
                    </a>
                </div>
            </div>
            <br>
        {% endfor %}
    </div>

{% endblock content %}

route를 연결해주기 위해 상단에 {% load wagtailroutablepage_tags %}을 적용하였다. 

a 태그를 누르면 route 페이지로 이동하려고 하는데 Django url이 아닌 Wagtail의 routable url를 사용한다. 

 

<a href="{% routablepageurl page 'latest_blog_posts' %}">View Latest Posts Only</a>

여기서 살펴볼 것은 route데코레이터가 붙은 함수명을 사용한다는 것이다. (함수명이 길 때에는 name을 사용하면 된다.

@route(r'^latest/$', name="route_name"))으로 적어주고 
 
<a href="{% routablepageurl page 'route_name' %}">View Latest Posts Only</a>

으로 사용한다.)

 

2)

blog/latest_posts.html

{% extends "base.html" %}

{% load wagtailimages_tags %}

{% block content %}

    <div class="container">
        <h1>Latest Posts </h1>
        {% for post in posts %}
            <div class="row">
                <div class="col-sm-3">
                    {% image post.blog_image fill-250x250 as blog_img %}
                    <a href="{{ post.url }}">
                        <img src="{{ blog_img.url }}" alt="{{ blog_img.alt }}">
                    </a>
                </div>
                <div class="col-sm-9">
                    <a href="{{ post.url }}">
                        {{ post.custom_title }}
                    </a>
                </div>
            </div>
            <br>
        {% endfor %}
    </div>

{% endblock content %}

context['posts']에 최근 블로그 포스트가 담겨져 있으므로 기존 페이지와 사용방법에 큰 차이는 없다. 

 

Routable Page는 Ajax 통신에도 사용가능하고 GET방식을 이용하여 Server와 Templates간의 데이터 송수신에도 편리하게 이용할 수 있을 것이다.

'Back-End > Wagtail, Django' 카테고리의 다른 글

Wagtail 참고 사이트  (0) 2021.11.17
Wagtail git ignore setting  (0) 2021.11.16
Wagtail BaseSetting  (0) 2021.11.15
Wagtail Debug Toolbar(+ Django)  (0) 2021.11.13
Django, Wagtail Vue 로그인 연동  (0) 2021.11.12

Wagtail Admin Page에서 settings에 기능을 추가하는 방법에 대해서 다뤄보려고 한다. 

 

https://www.youtube.com/watch?v=jsan9SclzpI&list=PLMQHMcNi6ocsS8Bfnuy_IDgJ4bHRRrvub&index=14 

 

위 영상을 따라해서 만들었다. 

 

1. 새로운 App 생성

 

python manage.py startapp site_settings

Settings를 따로 관리하기 위해 App을 만들어준다. App을 만들었으니 base.py에 등록한다. 

 

settings/base.py

INSTALLED_APPS = [

    'site_settings',
]

apps.py와 models.py이외에는 필요가 없으니 나머지 views.py, admin.py, tests.py는 지워준다.(옵션 사항)

 

 

2. Model작성

 

site_settings/models.py

from django.db import models

from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel
from wagtail.contrib.settings.models import BaseSetting, register_setting


@register_setting
class SocialMediaSettings(BaseSetting):
    """Social media settings for our custom website."""
    
    facebook = models.CharField(blank=True, null=True, help_text="Facebook URL", max_length=30)
    twitter = models.CharField(blank=True, null=True, help_text="Twitter URL", max_length=30)
    youtube = models.CharField(blank=True, null=True, help_text="YouTube URL", max_length=30)
    
    panels = [
        MultiFieldPanel([
            FieldPanel("facebook"),
            FieldPanel("twitter"),
            FieldPanel("youtube"),
        ], heading="Social Media Settings")
    ]

위와 같이 모델을 작성해준다. 튜토리얼과 같이 SocialMedia를 관리하는 Setting을 만드려고 한다. 모델 작성하는 방법은 기존 모델 작성하는 방법과 같다. 다만 BaseSetting을 상속받아 Setting 페이지 양식으로 작성하고 

데코레이터(=@)를 사용하여 settings에 등록해준다. 

 

 

3. 설정 파일 수정

마이그레이션을 진행하고 admin page를 확인해보면 적용이 안되어 있을 것이다. setting을 수정하기 위해서는 setting에 2가지를 추가해줘야한다. 

 

settings/base.py

INSTALLED_APPS = [
	...
    'wagtail.contrib.forms',
    'wagtail.contrib.redirects',
    'wagtail.contrib.settings', # 추가
]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_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',
                'wagtail.contrib.settings.context_processors.settings', # 추가
            ],
        },
    },
]

1) INSTALLED_APPS에 'wagtail.contrib.settings'를 추가해준다. 

2) TEMPLATES에 wagtail.contrib.settings.context_processors.settings를 추가해준다. 

 

 

4. 적용 완료

 

정상적으로 적용된 것을 확인할 수 있다. Field에 각 사이트의 주소를 적어보자.

 

 

5. Templates에서 사용

home/home_page.html

    {% if settings.site_settings.SocialMediasettings.facebook %}
        <a href="{{ settings.site_settings.SocialMediaSettings.facebook }}">
            <i class="fab fa-facebook-f"></i>
        </a>
    {% endif %}
    {% if settings.site_settings.SocialMediasettings.twitter %}
        <a href="{{ settings.site_settings.SocialMediaSettings.twitter }}">
            <i class="fab fa-twitter"></i>
        </a>
    {% endif %}
    {% if settings.site_settings.SocialMediasettings.youtube %}
        <a href="{{ settings.site_settings.SocialMediaSettings.youtube }}">
            <i class="fab fa-youtube"></i>
        </a>
    {% endif %}

사용하는 방법은 settings.App 이름.클래스 이름.필드 이름으로 사용한다. 

'Back-End > Wagtail, Django' 카테고리의 다른 글

Wagtail git ignore setting  (0) 2021.11.16
Wagtail Routable Pages  (0) 2021.11.16
Wagtail Debug Toolbar(+ Django)  (0) 2021.11.13
Django, Wagtail Vue 로그인 연동  (0) 2021.11.12
Wagtail Rich Editor 기능 추가  (0) 2021.11.06

Django로 개발할 때 유용한 Tool인 Django Debug Toolbar를 설치하는 방법에 대해서 적어보려고 한다. 

문서의 내용은 Django에서 설치하는 방법이지만 현재 Wagtail을 사용하고 있기 때문에 Wagtail에서 사용하는 방법에 대해서 정리하려고 한다. 

 

Django에서 적용하고 싶은 사람은 공식 문서를 따라하면 될 것이다.

https://django-debug-toolbar.readthedocs.io/en/latest/installation.html

 

Installation — Django Debug Toolbar 3.2.2 documentation

Each of the following steps needs to be configured for the Debug Toolbar to be fully functional. Troubleshooting On some platforms, the Django runserver command may use incorrect content types for static assets. To guess content types, Django relies on the

django-debug-toolbar.readthedocs.io

 

 

1. Django Debug Toolbar 설치

python -m pip install django-debug-toolbar

 

 

2. Module 적용

wagtail settings에는 base.py, dev.py, production.py가 있다. 

 

1)base.py

This file is for global settings that will be used in both development and production. Aim to keep most of your configuration in this file.

 

2)dev.py

This file is for settings that will only be used by developers. For example: DEBUG = True

 

3)production.py

This file is for settings that will only run on a production server. For example: DEBUG = False

 

4)local.py

This file is used for settings local to a particular machine. This file should never be tracked by a version control system.

 

1) base.py 는 공통적으로 사용하는 것을 정의 해 놓는다.

2) dev.py에는 로컬 단계. 즉 개발할 때 사용하는 것을 정의 해 놓는다.

3) production.py는 배포 서버를 위해 사용하는 것을 정의한다.

4) local.py 특정 기기에서 사용할 것을 정의한다. 

 

my_project/settings/dev.py

INSTALLED_APPS = INSTALLED_APPS + [
    'debug_toolbar',
]

INTERNAL_IPS = [
    '127.0.0.1',
]

MIDDLEWARE = MIDDLEWARE + [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

형식은 위와 같이 '+' 로 추가해준다고 적어주면 된다. 

 

INTERNAL_IPS는 로컬에서만 Debug Toolbar를 사용할 것이기 때문에 로컬 주소를 적어준다. 

 

MIDDLEWARE도 마찬가지로 dev.py에서 추가로 관리할 수 있다. 

 

 

3. URL 설정

my_project/urls.py

if settings.DEBUG:
    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns

    # Serve static and media files from development server
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    import debug_toolbar
    
    urlpatterns = urlpatterns + [
        path('__debug__/', include(debug_toolbar.urls)),
    ]

Debug 세팅을 위해 위와 같이 수정해준다. 역시나 마찬가지로 추가적인 설정이 있으면 '+'를 통해 종류별로 구별해서 정리할 수 있다. 

 

'__debug__'는 debug toolbar의 주소이다. (다른 App이랑 충돌이 안나는 선에서 아무거나 입력해도 된다. debug_toobar.urls만 명시해주면 된다. )

 

 

 

 

4. 적용 확인

python manage.py runserver

서버를 실행하고 웹 페이지에 들어가보면 적용이 되어 있는 것을 확인할 수 있다. Debug Toolbar를 통해 개발하는데 구체적인 정보를 얻을 수 있다. 

'Back-End > Wagtail, Django' 카테고리의 다른 글

Wagtail Routable Pages  (0) 2021.11.16
Wagtail BaseSetting  (0) 2021.11.15
Django, Wagtail Vue 로그인 연동  (0) 2021.11.12
Wagtail Rich Editor 기능 추가  (0) 2021.11.06
Wagtail Admin Page 한글 설정  (0) 2021.11.04

+ Recent posts