Commits

Anonymous committed 0577667

Copied code over from existing project - will begin working to adapt and improve it.

  • Participants
  • Parent commits 3ff3e5f

Comments (0)

Files changed (5)

+syntax: regexp
+^\.project$
+syntax: regexp
+^\.pydevproject$
+For installation instructions and other information, please see the Bitbucket
+wiki at: http://bitbucket.org/bkonkle/django-ajaxcomments/wiki/Home
+
+Thanks!

File src/ajaxcomments/media/js/comment-post.js

+$(document).ready(function() {
+    previewed = false;
+    
+    commentBusy = false;
+});
+
+function commentAjax() {
+    $('div.comment-error').remove();
+    
+    if (commentBusy) {
+        $('#comment-form').before('\
+            <div class="comment-error">\
+                Your comment is currently in the process of posting.\
+            </div>\
+        ');
+        $('div.comment-error').fadeOut(2000);
+        
+        return false;
+    }
+    
+    comment = $('#comment-form').serialize();
+    
+   
+    // Add a wait animation
+    $('input.submit-post').after('\
+        <img src="/static/adoleo/img/ajax-loader.gif" alt="Please wait..."\
+            class="ajax-loader" />\
+    ');
+    
+    // Indicate that the comment is being posted
+    $('p.submit').after('\
+        <div class="comment-waiting" style="display: none;">\
+            One moment while the comment is posted. . .\
+        </div>\
+    ');
+    $('div.comment-waiting').fadeIn(1000);
+    
+    commentBusy = true;
+    
+    // Use AJAX to post the comment.
+    $.post('/ajax/comment/post/', comment, function(data) {
+        commentBusy = false;
+        
+        // Remove the wait animation and message
+        $('.ajax-loader').remove();
+        $('div.comment-waiting').stop().remove();
+        
+        if (data.status == "success") {
+            commentSuccess(data);
+        } else {
+            commentFailure(data);
+        }
+    }, "json");
+    
+    return false;
+}
+
+function commentSuccess(data) {
+    email = $('#id_email').val();
+    comment = $('#id_comment').val();
+    name = $('#id_name').val();
+    url = $('#id_url').val();
+    
+    // Create an MD5 hash from the email address to use with Gravatar
+    gravatar = 'http://www.gravatar.com/avatar.php' +
+        '?default=&size=48&gravatar_id=' + $.md5(email);
+    
+    if ($('div#comments').children().length == 0) {
+        $('div#comments').prepend(
+            '<h2 class="comment-hd">1 comment so far:</h2>'
+        )
+    }
+    
+    comment_html = '\
+        <div class="comment" style="display: none;">\
+            <div class="comment-body">\
+                <a href="http://www.gravatar.com">\
+                    <img src="' + gravatar + '" /></a>\
+                <p>' + comment + '</p>\
+            </div>\
+        <div class="clear"></div>\
+        <p class="posted-by">Posted by <a href="' + url + '">' + 
+            name + '</a> 0 minutes ago.</p></div>\
+    ';
+    
+    $('#id_comment').val('');
+    
+    $('#comments').append(comment_html);
+    $('div.comment:last').show('slow');
+    
+    $('p.submit').after('\
+        <div class="comment-thanks">\
+            Thank you for your comment!\
+        </div>\
+    ');
+    $('div.comment-thanks').fadeOut(4000);
+}
+
+function commentFailure(data) {
+    $('p.submit').after('\
+        <div class="comment-error" style="display: none;">' + data.error +
+        '</div>\
+    ');
+    $('div.comment-error').fadeIn(1000);
+}

File src/ajaxcomments/urls.py

 from django.conf.urls.defaults import *
 
-# Uncomment the next two lines to enable the admin:
-# from django.contrib import admin
-# admin.autodiscover()
-
-urlpatterns = patterns('',
-    # Example:
-    # (r'^ajaxcomments/', include('ajaxcomments.foo.urls')),
-
-    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
-    # to INSTALLED_APPS to enable admin documentation:
-    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
-
-    # Uncomment the next line to enable the admin:
-    # (r'^admin/(.*)', admin.site.root),
-)
+urlpatterns = patterns('ajaxcomments.views',
+    url(r'^comment/post/$',
+        view='ajax_comment_post',
+        name='ajax_comment_post'),
+)

File src/ajaxcomments/views.py

+from django.shortcuts import render_to_response
+from django.template import RequestContext
+from django import http
+from django.conf import settings
+from django.core.exceptions import ObjectDoesNotExist
+from django.db import models
+from django.template.loader import render_to_string
+from django.utils.html import escape
+from django.contrib import comments
+from django.contrib.comments import signals
+from django.utils import simplejson
+from time import sleep
+
+def ajax_comment_post(request):
+    if request.method == "POST":
+        # 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:
+            error = "Missing content_type or object_pk field." 
+            status = simplejson.dumps({'status': 'error', 'error': error})
+            return http.HttpResponseServerError(status,
+                                                mimetype="application/json")
+        try:
+            model = models.get_model(*ctype.split(".", 1))
+            target = model._default_manager.get(pk=object_pk)
+        except TypeError:
+            error = "Invalid content_type value: %r" % escape(ctype) 
+            status = simplejson.dumps({'status': 'error', 'error': error})
+            return http.HttpResponseServerError(status,
+                                                mimetype="application/json")
+        except AttributeError:
+            error = "The given content-type %r " % escape(ctype)
+            error += "does not resolve to a valid model."
+            status = simplejson.dumps({'status': 'error', 'error': error})
+            return http.HttpResponseServerError(status,
+                                                mimetype="application/json")
+        except ObjectDoesNotExist:
+            error = "No object matching content-type %r " % escape(ctype)
+            error += "and object PK %r exists." % escape(object_pk)
+            status = simplejson.dumps({'status': 'error', 'error': error})
+            return http.HttpResponseServerError(status,
+                                                mimetype="application/json")
+    
+        # Construct the comment form
+        form = comments.get_form()(target, data=data)
+    
+        # Check security information
+        if form.security_errors():
+            error = "The comment form failed security verification: "
+            error += "%s" % escape(str(form.security_errors()))
+            status = simplejson.dumps({'status': 'error', 'error': error})
+            return http.HttpResponseServerError(status,
+                                                mimetype="application/json")
+    
+        if form.errors:
+            error = ""
+            for e in form.errors:
+                error += "Error in the %s field: %s" % (e, form.errors[e])
+            status = simplejson.dumps({'status': 'error', 'error': error})
+            return http.HttpResponse(status, mimetype="application/json")
+    
+        # 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 == False:
+                error = 'Signal comment_will_be_posted receiver '
+                error += '%r killed the comment' % receiver.__name()
+                status = simplejson.dumps({'status': 'error', 'error': error})
+                return http.HttpResponseServerError(status,
+                                                    mimetype="application/json")
+    
+        # Save the comment and signal that it was saved
+        comment.save()
+        signals.comment_was_posted.send(
+            sender  = comment.__class__,
+            comment = comment,
+            request = request
+        )
+        
+        status = simplejson.dumps({'status': "success"})
+        return http.HttpResponse(status, mimetype="application/json")
+    
+    # Raise a 404 error because POST was not used.
+    raise http.Http404