How to integrate djangobb in an existing project?

纵然是瞬间 提交于 2020-01-07 09:26:09

问题


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

This is the installation guidelines mentioned on djangobb support. I'm stuck after installing the requirements.txt. How do I integrate djangobb to my existing project. Django noob here hence the need of help.


回答1:


Here you can find my guide writen 2 months ago. For now I see that this guide can be few steps less, but it does not change the result :) so I don't see big reason to re-write it. If you have any question once the guide is read, pls ask.


Currently DjangoBB consist from 2 Git pieces:

  • 3 branches for App itself (stable, default and bootstrap3)
  • 2 branches for Project (default and dimka665/*********)

In this tutorial we are going to use bolded versions of DjangoBB.

1) stable/default/botstrap3 — means DjangoBB_Forum as App itself. Stable branch has the latest version of code so lets use it.

Source

Zip archive

2) default — Django's skeleton project structure with all settings (urls.py, settings.py, templates, etc) needed to launch 'DjangoBB_Forum app'. This is JUST the project skeleton (similiar to ./manage.py startproject) and here DjangoBB_Forum as App is NOT included.

Source

Zip archive

Lets download both archives, extract them and for convenience rename 2 folders that we've got (both have original name 'slav0nic-djangobb-****) to DjangoBB_App for 'stable' App's branch and to DjangoBB_Project for 'default' Project's branch. (We age going to combine files\datas of both archives)


Instalation.

For today (19.09.2015) the latest version of Django is 1.8.4. This tutorial also is 100% applicable for 1.8.2 and 1.8.3. I've not tested earlier versions of Django.

Now DjangoBB_Forum requirements look like this:

  • Django>=1.6,<1.9 (the actual latest stable version is 1.8.4)

  • django-haystack>=2.1.0,<2.4 (actual version for the time of this tutorial is 2.4)

  • Pillow>=2.1.0 (actual version is 2.9.0)
  • postmarkup (actual version is 1.2.2)
  • pygments (actual version is 2.0.2)
  • pytz>=2015.4 (this is actual version)
  • django-pagination-py3==1.1.1 (this actual version)
  • django-allauth (actual version is 0.23.0)
  • django-messages (actual version is 0.5.1)
  • django-nocaptcha-recaptcha (actual version is 0.0.18)
  • whoosh (actual version is 2.7.0)

The biggest problem here with integration DjangoBB_Forum to existing project is settings, because they are different from user to user. I show you my structure as example, prepared urls.py and settings.py to let you to integrate new settings to your project easily with all necessary explanations. Before to use settings.py below, you need to change DATABASES section there with your DB settings. Also much more below you will see 2nd screen with labels for folders\files which explain you what to change in settings.py in, because you have for sure another absolute paths and possibly another relative paths.

Also want to mention, that on the screeens you will see instead of 'settings/settings.py' file, 3 other files (default_settings.py, development.py, production.py). In the manual, saying 'settings.py' I mean YOUR 'settings.py' file whatever it calls, instead of files on the screen.

Initial structure of our project which is ready to accept djangobb_forum (app_shows_and_times and app_places are used just to make feeling of the existing project to which we add djangobb_forum):

/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) Lets imagine that we have project_name/src folder somewhere in VirtualEnvironment (should be already installed (properly built-in feature of Python since v3.4)), which we are going to use as the project folder.

  1. Copy all the entire content from djangobb_project/basic_project/media/* to /bugaga.com/media/

  2. Copy all the entire content from djangobb_project/basic_project/templates/* to /bugaga.com/src/templates/

  3. Copy djangobb_project/basic_project/forms.py to /bugaga.com/bugaga.com/src/settings/

  4. Copy from djangobb_app/ the next stuff:

    • 'djangobb_forum' folder
    • 'requirements.txt' file
    • 'requirements_optional.txt' file to /bugaga.com/bugaga.com/src/
  5. Now you should have the next structure (new stuff marked by black arrows)

  1. activate your virtenv (see step #0)

  2. cd to '/bugaga.com/bugaga.com/src/' (here is my path to my project)

  3. run 'pip install -r requirements.txt' (pip should be also installed long time ago)

  4. run 'pip install -r requirements_optional.txt'

  5. run 'pip install django-nocaptcha-recaptcha'

  6. run 'pip install whoosh'

  7. in '/bugaga.com/bugaga.com/src/' create a file 'secret.txt' and put there any random string you like, for example 'asd423llkmasdi2'

  8. Now try to './manage.py runsever' and open http://127.0.0.1:8000/forum/. If you get error like: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. This means you need to properly set up your DataBase in '/bugaga.com/bugaga.com/src/settings/settings.py'. From the box (means by default) we have the next settings for 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.
    }
}

As I use PostgreSQL, I can provide DB template for 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. If you did not see the error above, then you should see the error below:

    django.db.utils.ProgrammingError: relation "djangobb_forum_forum" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "djangobb_…

:)

  1. run './manage.py migrate'

  2. If you got error:

    django.db.utils.ProgrammingError: relation "auth_user" does not exist

-> run './manage.py migrate auth'

  1. If you got error:

    psycopg2.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1

-> run './manage.py migrate sites'

  1. run './manage.py migrate' (it migrates the rest apps all together so you dont need to specify the name each of them).

  2. run './manage.py makemigrations'

  3. Again run './manage.py migrate'

  4. Before you can open in the browser your forum, you need to have an account ('./manage.py createsuperuser') othewise you will get errors:

    • in browser: User matching query does not exist.
    • in console: django.contrib.auth.models.DoesNotExist: User matching query does not exist.
  5. Also to avoid error:

    ImportError: No module named 'allauth.account.context_processors'

-> open 'bugaga.com/bugaga.com/src/settings/settings.py' and in the TEMPLATE_CONTEXT_PROCESSORS section comment (by #) 2 lines like this:

  #  'allauth.account.context_processors.account',
  #  'allauth.socialaccount.context_processors.socialaccount',
  1. Now we can open our forum but there is 1 remained issue with languages. To fix it, cd to '/src/djangobb_forum/' and run 'django-admin compilemessages'

  2. Now you can run './manage.py runserver' and welcome to DjangoBB_Forum http://127.0.0.1:8000/forum/



来源:https://stackoverflow.com/questions/33474341/how-to-integrate-djangobb-in-an-existing-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!