django链接到后端的注释功能不起作用

时间:2017-12-19 12:24:04

标签: django comments

将网站转移到具有更高python版本的另一台服务器后,将后端的链接工作到评论功能。有人知道问题出在哪里吗?谢谢。

我正在使用django 1.6(我希望我能尽快更新)

这是根级别 settings.py 中的代码(仅限重要部分)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.syndication',
    'django_comments',
    'blog',
    'hyper',
    'webmanager',
    'watson',
)
INSTALLED_APPS += ('django_summernote', )


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

)

ROOT_URLCONF = 'urls'
SITE_ID='1'
#WSGI_APPLICATION = 'marxelhino.wsgi.application'


# fluent-comments settings:
    FLUENT_COMMENTS_USE_EMAIL_MODERATION = True
    FLUENT_COMMENTS_MODERATE_AFTER_DAYS = 14
    FLUENT_COMMENTS_CLOSE_AFTER_DAYS = 60
    FLUENT_COMMENTS_AKISMET_ACTION = 'moderate'
    AKISMET_API_KEY = None # Add your Akismet key here to enable Akismet support
    AKISMET_IS_TEST = True # for development/example apps.

这是我在根级别 urls.py 中的代码

    from django.conf.urls import patterns, include, url
    from django.conf import settings
    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from marxelhino.feeds import Latest
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()
    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'marxelinho.views.home', name='home'),
        url(r'^$', 'blog.views.index', name='index'),
        url(r'^blog/(?P<slug>[a-zA-Z0-9_.-]+)/$$', 'blog.views.detail', name='detail'),
        url(r'^blog/by_year/(?P<year>\d{4})/$', 'blog.views.post_year', name='list-years'),
        url(r'^blog/(?P<year>\d{4})/(?P<month>\d{1,2})/$', 'blog.views.post_month', name='list-month'),
        url(r'^blog/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', 'blog.views.post_day', name='list-day'),
        url(r'^category/(?P<slug>[a-zA-Z0-9_./-]+)/$$', 'blog.views.category_detail', name='category_detail'),
        #url(r'^blog/comments/', include('fluent_comments.urls')),
        url(r'^comments/', include('django_comments.urls')),
        (r'^latest/feed/$', Latest()),
        url(r'^tinymce/', include('tinymce.urls')),
        url(r'^search/', include('search.urls')),
        url(r'^summernote/', include('django_summernote.urls')),
        url(r'^accounts/', include('registration.backends.default.urls')),
        # Uncomment the admin/doc line below to enable admin documentation:
         url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
        # Uncomment the next line to enable the admin:
        url(r'^admin/', include(admin.site.urls)),
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.STATIC_ROOT}),
        (r'^media/(?P<path>.*)$', 'django.views.static.serve',
       # (r'^suche/', include('haystack.urls')),
            {'document_root': settings.MEDIA_ROOT}),
    )

django_comments

文件夹中 urls.py 中的代码
from django.conf.urls import patterns, url

urlpatterns = patterns('django_comments.views',
    url(r'^post/$',          'comments.post_comment',       name='comments-post-comment'),
    url(r'^posted/$',        'comments.comment_done',       name='comments-comment-done'),
    url(r'^flag/(\d+)/$',    'moderation.flag',             name='comments-flag'),
    url(r'^flagged/$',       'moderation.flag_done',        name='comments-flag-done'),
    url(r'^delete/(\d+)/$',  'moderation.delete',           name='comments-delete'),
    url(r'^deleted/$',       'moderation.delete_done',      name='comments-delete-done'),
    url(r'^approve/(\d+)/$', 'moderation.approve',          name='comments-approve'),
    url(r'^approved/$',      'moderation.approve_done',     name='comments-approve-done'),
)

urlpatterns += patterns('',
    url(r'^cr/(\d+)/(.+)/$', 'django.contrib.contenttypes.views.shortcut', name='comments-url-redirect'),
)

此代码位于 fluent_comments 文件夹中,文件 views.py

from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.http import HttpResponse, HttpResponseBadRequest
from django.template.loader import render_to_string
from django.template import RequestContext
from django.contrib import comments
from django.contrib.comments import signals
from django.contrib.comments.views.comments import CommentPostBadRequest
from django.utils.html import escape
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_POST
from fluent_comments import appsettings
import json


@csrf_protect
@require_POST
def post_comment_ajax(request, using=None):
    """
    Post a comment, via an Ajax call.
    """
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    # This is copied from django.contrib.comments.
    # Basically that view does too much, and doesn't offer a hook to change the rendering.
    # The request object is not passed to next_redirect for example.
    #
    # This is a separate view to integrate both features. Previously this used django-ajaxcomments
    # which is unfortunately not thread-safe (it it changes the comment view per request).


    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        object_pk = long(object_pk)
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except ValueError:
        return CommentPostBadRequest("Invalid object_pk value: {0}".format(escape(object_pk)))
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: {0}".format(escape(ctype)))
    except AttributeError:
        return CommentPostBadRequest("The given content-type {0} does not resolve to a valid model.".format(escape(ctype)))
    except ObjectDoesNotExist:
        return CommentPostBadRequest("No object matching content-type {0} and object PK {1} exists.".format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest("Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}".format(escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest("The comment form failed security verification: {0}".format)

    # If there are errors or if we requested a preview show the comment
    if preview:
        comment = form.get_comment_object() if not form.errors else None
        return _ajax_result(request, form, "preview", comment, object_id=object_pk)
    if form.errors:
        return _ajax_result(request, form, "post", object_id=object_pk)


    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    for (receiver, response) in responses:
        if response is False:
            return CommentPostBadRequest("comment_will_be_posted receiver {0} killed the comment".format(receiver.__name__))

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )

    return _ajax_result(request, form, "post", comment, object_id=object_pk)


def _ajax_result(request, form, action, comment=None, object_id=None):
    # Based on django-ajaxcomments, BSD licensed.
    # Copyright (c) 2009 Brandon Konkle and individual contributors.
    #
    # This code was extracted out of django-ajaxcomments because
    # django-ajaxcomments is not threadsafe, and it was refactored afterwards.

    success = True
    json_errors = {}

    if form.errors:
        for field_name in form.errors:
            field = form[field_name]
            json_errors[field_name] = _render_errors(field)
        success = False

    json_return = {
        'success': success,
        'action': action,
        'errors': json_errors,
        'object_id': object_id,
        'use_threadedcomments': bool(appsettings.USE_THREADEDCOMMENTS),
    }

    if comment is not None:
        context = {
            'comment': comment,
            'action': action,
            'preview': (action == 'preview'),
            'USE_THREADEDCOMMENTS': appsettings.USE_THREADEDCOMMENTS,
        }
        comment_html = render_to_string('comments/comment.html', context, context_instance=RequestContext(request))

        json_return.update({
            'html': comment_html,
            'comment_id': comment.id,
            'parent_id': None,
            'is_moderated': not comment.is_public,   # is_public flags changes in comment_will_be_posted
        })
        if appsettings.USE_THREADEDCOMMENTS:
            json_return['parent_id'] = comment.parent_id

    json_response = json.dumps(json_return)
    return HttpResponse(json_response, content_type="application/json")


def _render_errors(field):
    """
    Render form errors in crispy-forms style.
    """
    template = '{0}/layout/field_errors.html'.format(appsettings.CRISPY_TEMPLATE_PACK)
    return render_to_string(template, {
        'field': field,
        'form_show_errors': True,
    })

此代码位于 fluent_comments 文件夹中,文件 urls.py

try:
    # Django 1.6 requires this
    from django.conf.urls import url, patterns, include
except ImportError:
    # Django 1.3 compatibility, kept in minor release
    from django.conf.urls.defaults import url, patterns, include


urlpatterns = patterns('fluent_comments.views',
    url(r'^post/ajax/$', 'post_comment_ajax', name='comments-post-comment-ajax'),
    url(r'', include('django.contrib.comments.urls')),
)

0 个答案:

没有答案