1、配置setting
代码语言:javascript复制INSTALLED_APPS = [
....
'django.contrib.sites',
'django.contrib.flatpages',
....
]
SITE_ID = 1
MIDDLEWARE = [
...
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
...
]
2、配置urls.py
代码语言:javascript复制urlpatterns = [
path('pages/', include('django.contrib.flatpages.urls')),
]
或者
from django.contrib.flatpages import views
# Your other patterns here
urlpatterns = [
path('<path:url>', views.flatpage),
]
再或者
from django.contrib.flatpages import views
urlpatterns = [
path('about-us/', views.flatpage, {'url': '/about-us/'}, name='about'),
path('license/', views.flatpage, {'url': '/license/'}, name='license'),
]
3、添加admin
自带admin后台
代码语言:javascript复制from django.contrib import admin
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import gettext_lazy as _
# Define a new FlatPageAdmin
class FlatPageAdmin(FlatPageAdmin):
fieldsets = (
(None, {'fields': ('url', 'title', 'content', 'sites')}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': (
'enable_comments',
'registration_required',
'template_name',
),
}),
)
# Re-register FlatPageAdmin
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)
xadmin后台
代码语言:javascript复制from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import gettext_lazy as _
class FlatPageAdmin(object):
fieldsets = (
(None, {'fields': ('url', 'title', 'content', 'sites')}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ( 'enable_comments',
'registration_required',
'template_name',
),
}),
)
xadmin.site.register(FlatPage, FlatPageAdmin)
数据库迁移
代码语言:javascript复制python manage.py makemigrations
python manage.py migrate
python manage.py runserver 8000
4、测试成功
这里注意一点,setting里配置SITE_ID = 1
要一致
5、添加模板
添加页面flatpages/default.html
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
{{ flatpage.content }}
</body>
</html>
或者
{% load flatpages %}
{% get_flatpages as flatpages %}
<ul>
{% for page in flatpages %}
<li><a href="{{ page.url }}">{{ page.title }}</a></li>
{% endfor %}
</ul>
其他
代码语言:javascript复制{% get_flatpages '/about/' as about_pages %}
{% get_flatpages about_prefix as about_pages %}
{% get_flatpages '/about/' for someuser as about_pages %}
配置访问成功。
6、自定义内容添加富文本编辑器
前提是django配置好ckeditor编辑,参考:Django添加ckeditor富文本编辑器
修改Lib/site-packages/django/contrib/flatpages/models.py下的
代码语言:javascript复制class FlatPage(models.Model):
content = models.TextField(_('content'), blank=True)
修改成:
代码语言:javascript复制from ckeditor_uploader.fields import RichTextUploadingField
class FlatPage(models.Model):
content = RichTextUploadingField(_('content'), blank=True)
参考文章https://docs.djangoproject.com/zh-hans/2.1/ref/contrib/flatpages/