如何将 djangobb 集成到现有项目中?

How to integrate djangobb in an existing project?

wget https://bitbucket.org/slav0nic/djangobb_project/get/tip.tar.gz
tar zxvf tip.tar.gz
cd slav0nic-djangobb_project-tip/
pip install -r requirements.txt
cd basic_project/
touch local_settings.py
 #set DATABASE
 ./manage.py syncdb --all
 ./manage.py collectstatic
 ./manage.py runserver

这是djangobb 支持中提到的安装指南。安装 requirements.txt 后我卡住了。如何将 djangobb 集成到我现有的项目中。 Django 菜鸟在这里因此需要帮助。

在这里你可以找到我 2 个月前写的指南。现在我看到这个指南可以少几个步骤,但它不会改变结果 :) 所以我没有看到重写它的重要理由。阅读指南后如有任何疑问,请提问。


目前 DjangoBB 由 2 Git 件组成:

  • App 本身的 3 个分支(stable,default 和 bootstrap3)
  • 2 个项目分支(默认 和 dimka665/*********)

在本教程中,我们将使用粗体版本的 DjangoBB。

1) stable/default/botstrap3 — 表示 DjangoBB_Forum 作为 App 本身。 稳定分支有最新版本的代码所以让我们使用它。

Source

Zip archive

2) default — Django 的骨架项目结构,包含启动 'DjangoBB_Forum app' 所需的所有设置(urls.py、settings.py、模板等)。这只是项目框架(类似于 ./manage.py startproject),这里 DjangoBB_Forum 因为不包括应用程序。

Source

Zip archive

让我们下载这两个档案,解压它们并为方便起见将我们得到的 2 个文件夹(都有原始名称'slav0nic-djangobb-****)重命名为 DjangoBB_App for 'stable'应用的分支和 'default' 项目分支的 DjangoBB_Project。 (我们年龄将合并 files\datas 两个档案)


正在安装。

今天 (19.09.2015) Django 的最新版本是 1.8.4。本教程也 100% 适用于 1.8.2 和 1.8.3。我没有测试过早期版本的 Django。

现在 DjangoBB_Forum 要求如下所示:

  • Django>=1.6,<1.9(实际最新稳定版是1.8.4)

  • django-haystack>=2.1.0,<2.4(此时的实际版本 教程是 2.4)

  • Pillow>=2.1.0(实际版本为2.9.0)
  • postmarkup(实际版本为1.2.2)
  • pygments(实际版本为2.0.2)
  • pytz>=2015.4(这是实际版本)
  • django-pagination-py3==1.1.1(这个实际版本)
  • django-allauth(实际版本为0.23.0)
  • django-messages(实际版本为0.5.1)
  • django-nocaptcha-recaptcha(实际版本为0.0.18)
  • 呼呼(实际版本为2.7.0)

与现有项目集成 DjangoBB_Forum 的最大问题是设置,因为它们因用户而异。我向您展示了我的结构示例,准备了 urls.py 和 settings.py 让您轻松地将新设置集成到您的项目中,并提供所有必要的解释。在下面使用 settings.py 之前,您需要使用您的数据库设置更改那里的 DATABASES 部分。在下面还有更多内容,您将看到带有 folders\files 标签的第二个屏幕,它向您解释了 settings.py 中的更改内容,因为您肯定有另一个绝对路径,可能还有另一个相对路径。

还想提一下,在屏幕上您将看到 3 个其他文件(default_settings.py、development.py、production.py),而不是 'settings/settings.py' 文件。在手册中,说 'settings.py' 我的意思是你的 'settings.py' 文件,无论它叫什么,而不是屏幕上的文件。

我们项目的初始结构已准备好接受 djangobb_forum(app_shows_and_times 和 app_places 仅用于了解我们添加 [=328= 的现有项目]):

/src/bugaga/urls.py

"""bugaga URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""

from django.conf.urls import *
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static

from djangobb_forum import settings as forum_settings
from djangobb_forum.sitemap import SitemapForum, SitemapTopic


sitemaps = {
    'forum': SitemapForum,
    'topic': SitemapTopic,
}

urlpatterns = patterns('',
    # Admin
    url(r'^admin/', include(admin.site.urls)),

    # Sitemap
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),

    #My_Apps
    url(r'^places/', include('app_places.urls')),
    url(r'^shows/', include('app_shows_and_times.urls')),

    # DjangoBB_Forum
    url(r'^forum/account/', include('allauth.urls')),
    url(r'^forum/', include('djangobb_forum.urls', namespace='djangobb')),
)

# PM Extension
if (forum_settings.PM_SUPPORT):
    urlpatterns += patterns('',
        url(r'^forum/pm/', include('django_messages.urls')),
   )

if (settings.DEBUG):
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

/src/bugaga/settings/development.py

# -*- coding: utf-8 -*-
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

DEBUG = True
TEMPLATE_DEBUG = DEBUG
#print ("base dir path", BASE_DIR)

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name_of_db',
        'USER': 'login_to_db',
        'PASSWORD': 'pass_to_db',
        'HOST': 'localhost',
        'PORT': '',
    }
}

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

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'ru-RU'

LANGUAGES = (
    ('ca', 'Catalan'),
    ('cs', 'Czech'),
    ('de', 'German'),
    ('en', 'English'),
    ('es', 'Spanish'),
    ('fo', 'Faroese'),
    ('fr', 'France'),
    ('it', 'Italian'),
    ('lt', 'Lithuanian'),
    ('mn', 'Mongolian'),
    ('nl', 'Dutch'),
    ('pl', 'Polish'),
    ('ru', 'Russian'),
    ('uk_UA', 'Ukrainian'),
    ('vi', 'Vietnamese'),
    ('zh_CN', 'Chinese'),
)

SITE_ID = 1

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Kiev'
USE_TZ = True

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# STATIC_ROOT is where the static files get placed from STATIC_URL and STATICFILES_DIRS
# when they are collected by "manage.py collectstatic". Static files are used by Apache\nginx
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
#When you’re developing using Django’s development server, you won’t have anything to do with this setting.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = "/home/antonio/projects/bugaga.com/static/"

# URL prefix for static files in your apps
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# STATICFILES_DIRS is a setting you use to declare non app-specific static files
# You can prefixes for templates, as STATICFILES_DIRS = (("downloads", "/opt/webfiles/stats"),)
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    #'/var/www/static/',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
     'django.contrib.staticfiles.finders.FileSystemFinder', # is default; responsible for STATICFILES_DIRS
     'django.contrib.staticfiles.finders.AppDirectoriesFinder', # is default; responsible for $app_name/static/
     'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/antonio/projects/bugaga.com/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'YOUR_SECRET_KEY GENERATED BY DJANGO'

# Make this unique, and don't share it with anybody.

if not hasattr(globals(), 'SECRET_KEY'):
    SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
    try:
        SECRET_KEY = open(SECRET_FILE).read().strip()
    except IOError:
        try:
            from random import choice
            import string
            symbols = ''.join((string.lowercase, string.digits, string.punctuation ))
            SECRET_KEY = ''.join([choice(symbols) for i in range(50)])
            secret = file(SECRET_FILE, 'w')
            secret.write(SECRET_KEY)
            secret.close()
        except IOError:
            raise Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

    #DjangoBB_Forum part
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'pagination.middleware.PaginationMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',

    'djangobb_forum.middleware.LastLoginMiddleware',
    'djangobb_forum.middleware.UsersOnline',
    'djangobb_forum.middleware.TimezoneMiddleware',
)

ROOT_URLCONF = 'bugaga.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # Directories where the engine should look for template source files, in search order.
        # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
        'DIRS': [os.path.join(BASE_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',

                #DjangoBB_Forum part
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',

                'django_messages.context_processors.inbox',
                #'allauth.account.context_processors.account', #not required since v0.21.0
                #'allauth.socialaccount.context_processors.socialaccount', #not required since v0.21.0

                'djangobb_forum.context_processors.forum_settings',
            ],
            #DjangoBB_Forum part
             #'loaders': [
             #    'django.template.loaders.filesystem.Loader', #is the same as DIRS [] not empty
             #    'django.template.loaders.app_directories.Loader', #is the same as APP_DIRS = True
             #    'django.template.loaders.eggs.Loader',
             #]
        },
    },
]

PREREQ_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MY_APPS = [
    'app_places',
    'app_shows_and_times',
]

DJANGOBB_APPS = [
    'django.contrib.sites', #required by django-allauth
    'django.contrib.sitemaps',
    'django.contrib.admindocs',
    'django.contrib.humanize',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.openid',
    #'allauth.socialaccount.providers.facebook', # at first you need to configure Facebook or
    # you will get Error: No Facebook app configured: please add a SocialApp using the Django admin
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.twitter',
    'allauth.socialaccount.providers.vk',

    'pagination',
    'haystack',
    'django_messages',
    'nocaptcha_recaptcha',

    'djangobb_forum',
]

INSTALLED_APPS = PREREQ_APPS + MY_APPS + DJANGOBB_APPS

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

try:
    import mailer
    INSTALLED_APPS += ('mailer',)
    EMAIL_BACKEND = "mailer.backend.DbBackend"
except ImportError:
    pass

try:
    import south
    INSTALLED_APPS += ('south',)
    SOUTH_TESTS_MIGRATE = False
except ImportError:
    pass

FORCE_SCRIPT_NAME = ''

# Haystack settings
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(BASE_DIR, 'djangobb_forum/djangobb_index'),
        'INCLUDE_SPELLING': True,
    },
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

# Account settings
ACCOUNT_ACTIVATION_DAYS = 10
LOGIN_REDIRECT_URL = '/forum/'
LOGIN_URL = '/forum/account/login/'
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
)

# Cache settings
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True

# Allauth
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_SIGNUP_FORM_CLASS = 'bugaga.forms.SignupForm'

try:
    from local_settings import *
except ImportError:
    pass

(0) 假设我们在 VirtualEnvironment 的某个地方有 project_name/src 文件夹(应该已经安装了(自 v3.4 以来 Python 的正确内置功能)),我们将要用作项目文件夹。

  1. 复制全部内容 djangobb_project/basic_project/media/* 到 /bugaga.com/media/

  2. 复制全部内容 djangobb_project/basic_project/templates/* 到 /bugaga.com/src/templates/

  3. 复制 djangobb_project/basic_project/forms.py 到 /bugaga.com/bugaga.com/src/settings/

  4. 复制自 djangobb_app/ 下一篇:

    • 'djangobb_forum' 文件夹
    • 'requirements.txt' 文件
    • 'requirements_optional.txt' 文件 到 /bugaga.com/bugaga.com/src/
  5. 现在你应该有下一个结构(黑色箭头标记的新内容)

  1. 激活您的 virtenv(参见步骤 #0)

  2. cd 到'/bugaga.com/bugaga.com/src/'(这是我的项目路径)

  3. 运行 'pip install -r requirements.txt'(pip应该早就安装好了)

  4. 运行 'pip install -r requirements_optional.txt'

  5. 运行 'pip install django-nocaptcha-recaptcha'

  6. 运行 'pip install whoosh'

  7. in '/bugaga.com/bugaga.com/src/' 创建一个文件 'secret.txt' 并把你喜欢的任何随机字符串放在那里,例如 'asd423llkmasdi2'

  8. 现在尝试'./manage.py 运行服务器'并打开http://127.0.0.1:8000/forum/。如果您收到如下错误: settings.DATABASES 配置不正确。请提供引擎值。查看设置文档以获取更多详细信息。 这意味着您需要在“/bugaga.com/bugaga.com/src/settings/settings.py”中正确设置您的数据库。 从框中(默认情况下)我们有 DB 的下一个设置:

.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

由于我使用PostgreSQL,我可以提供PostgreSQL的数据库模板:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name_of_db',
        'USER': 'login_to_db',
        'PASSWORD': 'pass_to_db',
        'HOST': 'localhost',
        'PORT': '',
    }
}
  1. 如果您没有看到上面的错误,那么您应该会看到下面的错误:

    django.db.utils.ProgrammingError: 关系 "djangobb_forum_forum" 不存在 第 1 行:...user"."is_active", "auth_user"."date_joined" FROM "djangobb_...

:)

  1. 运行'./manage.py迁移'

  2. 如果出现错误:

    django.db.utils.ProgrammingError: 关系 "auth_user" 不存在

-> 运行 './manage.py 迁移授权'

  1. 如果出现错误:

    psycopg2.ProgrammingError: 关系 "django_site" 不存在 第 1 行:SELECT (1) AS "a" FROM "django_site" LIMIT 1

-> 运行 './manage.py 迁移站点'

  1. 运行 './manage.py migrate'(它将其余应用程序一起迁移,因此您无需指定每个应用程序的名称)。

  2. 运行 './manage.py makemigrations'

  3. 再次运行'./manage.py迁移'

  4. 在浏览器中打开您的论坛之前,您需要有一个帐户 ('./manage.py createsuperuser') 否则您会收到错误消息:

    • 在浏览器中:用户匹配查询不存在。
    • 在控制台中:django.contrib.auth.models.DoesNotExist:用户匹配查询不存在。
  5. 还要避免错误:

    ImportError: 没有名为 'allauth.account.context_processors'

  6. 的模块

-> 打开 'bugaga.com/bugaga.com/src/settings/settings.py' 并在 TEMPLATE_CONTEXT_PROCESSORS 部分注释(按 #)2 行,如下所示:

  #  'allauth.account.context_processors.account',
  #  'allauth.socialaccount.context_processors.socialaccount',
  1. 现在我们可以打开我们的论坛了,但是还有 1 个语言问题。要修复它,请 cd 到 '/src/djangobb_forum/' 和 运行 'django-admin compilemessages'

  2. 现在你可以运行'./manage.py运行服务器'欢迎使用DjangoBB_Forumhttp://127.0.0.1:8000/forum/