当前位置: 首页>>代码示例>>Python>>正文


Python models.Comment类代码示例

本文整理汇总了Python中django.contrib.comments.models.Comment的典型用法代码示例。如果您正苦于以下问题:Python Comment类的具体用法?Python Comment怎么用?Python Comment使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Comment类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_new_note

    def add_new_note(self,request, resource_type, resource_id):
        resource = request.resource
        
        if request.POST:
            
            #title = request.REQUEST.get('title');
            body  = request.REQUEST.get('body');
            
            new_comment = Comment(content_object = resource
                             ,site = DjangoSite.objects.all()[0]
                             ,user = request.user
                             ,user_name = request.user.username
                             ,user_email = request.user.email
                             ,user_url = ''
                             ,comment = body
                             ,ip_address = None
                             ,is_public = True
                             ,is_removed = False                       
                             )
                        
            new_comment.save()

            return self.response_success()
            
        return HttpResponse('')
开发者ID:aithonaltis,项目名称:gasistafelice,代码行数:25,代码来源:details.py

示例2: anon_comment

def anon_comment(request):
    if request.META.has_key('HTTP_REFERER'):
        referer = request.META.get('HTTP_REFERER', '')
    else:
        referer = str(followee_username)
    name = request.POST['anon_name']
    comment = request.POST['comment']
    inv_code = request.POST['inv_code']
    content_type_id= request.POST['content_type']
    object_id=request.POST['object_pk']
    if name and comment and inv_code :
        anon_invite = get_object_or_404(Anon_Conversation_Invite, code=inv_code)        
        email = anon_invite.receiver
        # code to create an inactive user
        user = User.objects.filter(email='anon_'+email)
        if not user:
            user=User(username='anon_'+email,email='anon_'+email,password='sha1$fd64a$2d7b3b5d6199ef44a08d56d1f1259019072d2',is_active=0)
            user.save()
            random_hash = sha.new(str(user.email)+str(random.random())).hexdigest()[:10]
            user_profile = User_Profile(user=user,display_name=user.username,hash=random_hash,quip_repeat_total=1,quip_total=1)
            user_profile.save()
            page_setting = PageSetting(user=user)
            page_setting.save()
            not_setting = NotificationSetting(user=user)
            not_setting.save()
            #adding default followee, this should be the one who invited him to conv
            #invitee = anon_invite.sender
            #follow_user_nomail(user,invitee.username,0)
        else:
            user = user[0]
        # code to add comment from that user, ip not being captured        
        content_type_kwip = get_object_or_404(ContentType,name='quip')
        comment = Comment(user=user,content_type=content_type_kwip,object_pk=object_id,comment=comment,is_public=1,site_id=1,valid_rating=0,is_removed=0)
        comment.save()
        quip = get_object_or_404(Quip,id=object_id)
        quip.comment_count+=1 # increment comment count
        quip.last_comment_at=datetime.datetime.now() # last comment time updated
        quip.save()
        cache_key = '%s_quip%s' % (settings.CACHE_MIDDLEWARE_KEY_PREFIX,object_id,)
        cache.delete(cache_key)
        obj_user = quip.account.user
        timestamp = quip.created_at.strftime("%Y/%b/%d/%H%M%S")
        link = str(obj_user.username)+'/kwips/'+timestamp.lower()
        subscribe_comments = request.POST.get('subscribe_comments', False)
	if subscribe_comments:
            anon_follow_comments(user, quip)        
        #link = str(request['url'][1:])
        params_for_mail = {'#_1':obj_user.username,'#_2':name, '#_3':format_it(quip.original),'#_4':link,'#_5':datetime.datetime.now().ctime()}
        if user != obj_user:
            send_mail(str(obj_user.email),'kwippy <[email protected]>','comment_anon',params_for_mail)
            send_im(obj_user,'comment',params_for_mail)
        # follow up notifications to users for comment by an anon 
        send_commentbyanon_emails(quip,user,name,params_for_mail,link)
        # follow up notifications to anons for comment by an anon 
        send_anon_comment_emails(quip,user,params_for_mail,link)
        return HttpResponseRedirect(referer)
        # code to add follow up notification settings
    else:
        # flash msg
        return HttpResponseRedirect(referer)
开发者ID:kwippy-com,项目名称:kwippycore,代码行数:60,代码来源:comment.py

示例3: import_comments

    def import_comments(self, entry, comment_nodes):
        """Loops over comments nodes and import then
        in django.contrib.comments"""
        for comment_node in comment_nodes:
            is_pingback = comment_node.find(
                '{%s}comment_type' % WP_NS).text == 'pingback'
            is_trackback = comment_node.find(
                '{%s}comment_type' % WP_NS).text == 'trackback'

            title = 'Comment #%s' % (comment_node.find(
                '{%s}comment_id/' % WP_NS).text)
            self.write_out(' > %s... ' % title)

            content = comment_node.find(
                '{%s}comment_content/' % WP_NS).text
            if not content:
                self.write_out(self.style.NOTICE('SKIPPED (unfilled)\n'))
                return

            submit_date = datetime.strptime(
                comment_node.find('{%s}comment_date' % WP_NS).text,
                '%Y-%m-%d %H:%M:%S')

            approvation = comment_node.find(
                '{%s}comment_approved' % WP_NS).text
            is_public = True
            is_removed = False
            if approvation != '1':
                is_removed = True
            if approvation == 'spam':
                is_public = False

            comment_dict = {
                'content_object': entry,
                'site': self.SITE,
                'user_name': comment_node.find(
                    '{%s}comment_author/' % WP_NS).text[:50],
                'user_email': comment_node.find(
                    '{%s}comment_author_email/' % WP_NS).text or '',
                'user_url': comment_node.find(
                    '{%s}comment_author_url/' % WP_NS).text or '',
                'comment': content,
                'submit_date': submit_date,
                'ip_address': comment_node.find(
                    '{%s}comment_author_IP/' % WP_NS).text or '',
                'is_public': is_public,
                'is_removed': is_removed, }
            comment = Comment(**comment_dict)
            comment.save()
            if approvation == 'spam':
                comment.flags.create(
                    user=entry.authors.all()[0], flag='spam')
            if is_pingback:
                comment.flags.create(
                    user=entry.authors.all()[0], flag='pingback')
            if is_trackback:
                comment.flags.create(
                    user=entry.authors.all()[0], flag='trackback')

            self.write_out(self.style.ITEM('OK\n'))
开发者ID:jfdsmit,项目名称:django-blog-zinnia,代码行数:60,代码来源:wp2zinnia.py

示例4: submit_comment

def submit_comment(request, event_slug):
    "submits a new comment associated with event"

    # checks for bad request
    if "comment_text" not in request.POST:
        return HttpResponseBadRequest()

    # get event object
    event = get_object_or_404(Event, slug=event_slug)

    # get participation object
    participation = get_object_or_404(Participation, accepted=True,
                                      person = request.user.get_profile(),
                                      event = event)

    # create a comment object and save
    comment = Comment(content_object=event, user=request.user, 
                      site=Site.objects.get_current(),
                      user_name=request.user.get_full_name(),
                      user_email=request.user.email,
                      comment=request.POST["comment_text"],
                      submit_date=datetime.now(), 
                      ip_address=request.META["REMOTE_ADDR"],
                      is_public=True)
    comment.save()

    # return an empty response
    return HttpResponse()
开发者ID:rodrigosetti,项目名称:demolition,代码行数:28,代码来源:views_post.py

示例5: comment

def comment(request):
    context = {}
    rid = request.POST['id']
    recipe = Recipe.objects.get(id = rid)
    context['recipe'] = recipe
    context['ingredients'] = recipe.ingredients.all()
    context['steps'] = recipe.steps.all()
    context['user'] = request.user
    context['rating'] = RatingForm()
    context['comment'] = CommentForm()
    context['comments'] = recipe.comments.all()
    context['autocompleteform'] = AutocompleteSearchForm()
    if request.method == 'GET':
        print 1
        return render(request, 'foodchaser/recipe_view.html', context)
    if request.method == 'POST':
        print 3 
        comment = CommentForm(request.POST)
    
    if not comment.is_valid():
        return render(request, 'foodchaser/recipe_view.html', context)
    
    text = Comment(text=comment.cleaned_data['comment'], \
                   owner=request.user)
    text.save()
    recipe.comments.add(text)
    
    context['comments'] = recipe.comments.all()
    
    return render(request, 'foodchaser/recipe_view.html', context)
开发者ID:ChX0602,项目名称:recipehub,代码行数:30,代码来源:handle_recipe.py

示例6: get_context_data

 def get_context_data(self, **kwargs):
     context = super(DetailItem, self).get_context_data(**kwargs)
     if self.object.__class__.__name__ == 'Serial':
         votes = Voting(self.object, self.request.user)
         context['watched'] = False
         context['truecomment'] = 0
         context['actors'] = self.object.actor_set.all()[:10]
         context['seasons'] = self.object.season_set.all()
         context['reviews'] = self.object.review_set.all()[:3]
         context['has_review'] = True
         context['votes'] = votes
         context['vote_succes'] = False
         if context['reviews'] == 0:
             context['has_review'] = False
         if self.request.user.is_authenticated():
             profile = self.request.user.get_profile()
             if profile.watched(self.object):
                 context['watched'] = True
         if 'postcomment' in self.request.POST and self.request.POST['comment'] is not None:
             type = ContentType.objects.get(app_label='sdata', model='serial')
             site = Site.objects.get(id=1)
             comments_count = str(Comment.objects.all().count())
             comment = Comment(content_type=type, content_object=self.object, object_pk=comments_count, site=site, user=self.request.user, comment=self.request.POST['comment'])
             comment.save()
             context['truecomment'] = 1
         if 'watch' in self.request.GET:
             profile.watch.add(serial)
             profile.save()
             context['watched'] = True
         if 'vote' in self.request.POST:
             votes.set_votes(self.request.POST['vote'])
             context['vote_succes'] = True
     return context
     
开发者ID:trofi4,项目名称:dj,代码行数:33,代码来源:cbvviews.py

示例7: test_get_user_name_from_comment

 def test_get_user_name_from_comment(self):
     comment = Comment(user=None, user_name='')
     self.assertEqual(publicweb_filters.get_user_name_from_comment(comment), "An Anonymous Contributor")
     comment.user_name = "Harry"
     self.assertEqual(publicweb_filters.get_user_name_from_comment(comment), "Harry")
     user = UserFactory()
     comment.user = user
     self.assertEqual(publicweb_filters.get_user_name_from_comment(comment), user.username)
开发者ID:TristramNorman,项目名称:econsensus,代码行数:8,代码来源:templatetags_test.py

示例8: delete_spam_comments

def delete_spam_comments(verbose=False):
    from django.contrib.comments.models import Comment
    spam_comments = Comment.objects.filter(is_public=False)
    deleted_count = spam_comments.count()
    
    for Comment in spam_comments:
    	Comment.delete()
    if spam_comments:
		print "Removed %s spam comments from database" % deleted_count
开发者ID:patrickbeeson,项目名称:blog,代码行数:9,代码来源:delete_spam_comments.py

示例9: testCommentNotifications

    def testCommentNotifications(self):
        c = Client()

        u = User.objects.create(username="peterpiper", email="[email protected]", 
                                is_superuser=False, is_staff=False)
        u.set_password('abcde')
        u.save()
        self.assertEquals(c.login(username='[email protected]', 
                                  password='abcde'), True)        
        
        p = BasicPost.objects.published()[0]
        
        response = c.post('/notifications/notify_comment/?next=/', 
                          {'name' : 'comment',
                           'app_label': 'post',
                           'model': p.get_class_name().lower(),
                           'pk': p.pk}, 
                          follow=True)
        self.assertEquals(response.status_code, 200)
        
        from notifications.models import Notification, CommentNotification, Recipient
        
        notifications = Notification.objects.select_subclasses()
        self.assertEquals(len(notifications), 1)
        self.assertEquals(type(notifications[0]), CommentNotification)
        
        recipients = Recipient.objects.all()
        self.assertEquals(len(recipients), 1)

        from django.contrib.comments.models import Comment
        from django.contrib.contenttypes.models import ContentType
        
        ct = ContentType.objects.get(app_label='post', 
                                     model=p.get_class_name().lower()) 
        cmt = Comment(content_type=ct, 
                    object_pk=p.pk, 
                    site=Site.objects.get_current(), 
                    user_name="joe", 
                    user_email='[email protected]', 
                    comment="Test comment")        
        cmt.save()
        
        from notifications.management.commands.processnotifications import Command
        
        cmd = Command()
        self.assertEquals(cmd.execute_notifications(['comment']), 1)
        
        response = c.post('/notifications/remove_comment_notification/?next=/', 
                           {'name' : 'comment',
                           'app_label': 'post',
                           'model': p.get_class_name().lower(),
                           'pk': p.pk}, 
                          follow=True)
        self.assertEquals(response.status_code, 200)

        recipients = Recipient.objects.all()
        self.assertEquals(len(recipients), 0)
开发者ID:joskid,项目名称:tbonline,代码行数:57,代码来源:tests.py

示例10: post

def post(request):
    """Returns a serialized object
    :param obj_id: ID of comment object
    :type obj_id: int
    :returns: json
    """
    guid = request.POST.get('guid', None)
    res = Result()   

    if guid:
        obj = getObjectsFromGuids([guid,])[0]
        c = Comment()
        c.comment = request.POST.get('comment', 'No comment')
        c.user = request.user
        c.user_name = request.user.get_full_name()
        c.user_email = request.user.email
        c.content_object = obj
        c.site_id = 1
        c.save()
        obj.comment_count = obj.comment_count + 1
        obj.save()

        __email(c, obj)

        res.append({'id': c.id, 'comment': c.comment})
        res.isSuccess = True
    else:
        res.isError = True
        res.message = "No guid provided"

    return JsonResponse(res)
开发者ID:davideilering,项目名称:Frog,代码行数:31,代码来源:comment.py

示例11: add

def add(request):
    form = AddForm()
    message = None
    if request.method == "POST":
        form = AddForm(request.POST)
        if form.is_valid():
            #create the objects with form.cleaned_data
            #can't use form.save() here, because it's not a modelform...
            print "form.cleaned_data",form.cleaned_data
            
            location,new = Location.objects.get_or_create(name=form.cleaned_data['location'])
            embed = SavedEmbed.objects.get(url=form.cleaned_data['url'])
            
            #TODO: convert date_uploaded to consistent format
            provider_name = embed.response['provider_name']
            try:
                date_uploaded = dateutil.parser.parse(form.cleaned_data['date_uploaded']) #TEMP, may fail
            except ValueError,e:
                return HttpResponseServerError("I don't know how to parse this date:",form.cleaned_data['date_uploaded'],"from",provider_name)
                
            #could start with copy of form.cleaned_data, but that would pull in shared form fields
            media_dict = {
                'date_uploaded':date_uploaded,
                'title':form.cleaned_data['title'],
                'slug':slugify(form.cleaned_data['title']),
                'location':location,
                'url':form.cleaned_data['url'],
                'embed':embed,
                'resolution':form.cleaned_data['resolution'],
                'author_name':form.cleaned_data['author_name'],
                'author_url':form.cleaned_data['author_url'],
                'license':form.cleaned_data['license'],
                'views':form.cleaned_data['views'],
                'tags':form.cleaned_data['tags'],
            }
            print "media_dict",media_dict
            media = Media(**media_dict)
            print "media obj",media
            media.save()
            
            comment_dict = {
                'user_name':form.cleaned_data['name'],
                'comment':form.cleaned_data['review'],
                'submit_date':datetime.now(),
                'ip_address':request.META['REMOTE_ADDR'],
                'content_type':ContentType.objects.get(app_label="mediacurate",model="media"),
                'object_pk':media.pk,
                'site_id':1 #assuming we're only using one site
            }
            print "comment_dict",comment_dict
            review = Comment(**comment_dict)
            review.save()
            message = "Thanks for adding <a href='%s'>%s</a>. Want to add another?" % (media.get_absolute_url(), media.title)
            #give the user a new form
            form = AddForm()
开发者ID:jlev,项目名称:videocurate,代码行数:55,代码来源:views.py

示例12: test_comment_post_save

 def test_comment_post_save(self):
     content_type = ContentType.objects.get(model='issue')
     comment = Comment()
     comment.user_name = self.user.username
     comment.user_email = self.user.email
     comment.content_type = content_type
     comment.object_pk = 1
     comment.comment = "This is a test comment"
     comment.site = Site.objects.get(id=settings.SITE_ID)
     comment.save()
     print comment.comment
开发者ID:digi604,项目名称:djtracker,代码行数:11,代码来源:tests.py

示例13: test_notify_on_comment

 def test_notify_on_comment(self):
     # post some comment
     comment = Comment()
     content_type = ContentType.objects.get(model='issue')
     comment = Comment()
     comment.user_name = 'somebody'
     comment.user_email = '[email protected]'
     comment.content_type = content_type
     comment.object_pk = 1
     comment.comment = "This is a test comment"
     comment.site = Site.objects.get(id=settings.SITE_ID)
     comment.save()
     
     self.assertEquals(len(mail.outbox), 3)        
     self.check_outbox(self.recipient_list, "DjTracker: [unittest-project]: New Comment on Issue #1 by somebody", comment.comment)        
开发者ID:digi604,项目名称:djtracker,代码行数:15,代码来源:tests.py

示例14: import_comments

    def import_comments(self, entry, comment_nodes):
        """Loops over comments nodes and import then
        in django.contrib.comments"""
        for comment_node in comment_nodes:
            is_pingback = comment_node.find("{http://wordpress.org/export/1.0/}comment_type").text == "pingback"
            is_trackback = comment_node.find("{http://wordpress.org/export/1.0/}comment_type").text == "trackback"

            title = "Comment #%s" % (comment_node.find("{http://wordpress.org/export/1.0/}comment_id/").text)
            self.write_out(" > %s... " % title)

            content = comment_node.find("{http://wordpress.org/export/1.0/}comment_content/").text
            if not content:
                self.write_out(self.style.NOTICE("SKIPPED (unfilled)\n"))
                return

            submit_date = datetime.strptime(
                comment_node.find("{http://wordpress.org/export/1.0/}comment_date").text, "%Y-%m-%d %H:%M:%S"
            )

            approvation = comment_node.find("{http://wordpress.org/export/1.0/}comment_approved").text
            is_public = True
            is_removed = False
            if approvation != "1":
                is_removed = True
            if approvation == "spam":
                is_public = False
            comment_dict = {
                "content_object": entry,
                "site": self.SITE,
                "user_name": comment_node.find("{http://wordpress.org/export/1.0/}comment_author/").text[:50],
                "user_email": comment_node.find("{http://wordpress.org/export/1.0/}comment_author_email/").text or "",
                "user_url": comment_node.find("{http://wordpress.org/export/1.0/}comment_author_url/").text or "",
                "comment": content,
                "submit_date": submit_date,
                "ip_address": comment_node.find("{http://wordpress.org/export/1.0/}comment_author_IP/").text or "",
                "is_public": is_public,
                "is_removed": is_removed,
            }
            comment = Comment(**comment_dict)
            comment.save()
            if approvation == "spam":
                comment.flags.create(user=entry.authors.all()[0], flag="spam")
            if is_pingback:
                comment.flags.create(user=entry.authors.all()[0], flag="pingback")
            if is_trackback:
                comment.flags.create(user=entry.authors.all()[0], flag="trackback")

            self.write_out(self.style.ITEM("OK\n"))
开发者ID:klipstein,项目名称:django-blog-zinnia,代码行数:48,代码来源:wp2zinnia.py

示例15: migrate_forum

def migrate_forum(db):
    category_id_map = {}
    for cat in fetch_all(db, "GDN_Category"):
        slug = CATEGORY_MAP.get(cat["UrlCode"], None)
        if not slug:
            continue
        category_id_map[cat["CategoryID"]] = (Category.objects.get(slug=slug), cat["UrlCode"])

    copied_posts, copied_comments = 0, 0
    for thread in fetch_all(db, "GDN_Discussion"):
        if thread["CategoryID"] not in category_id_map:
            continue
        cat, urlcode = category_id_map.get(thread["CategoryID"])
        new_post = Post(
            pk=thread["DiscussionID"],
            category=cat,
            title=(thread["Name"] if CATEGORY_MAP[urlcode] != "old" else ("[%s] " % urlcode) + thread["Name"]),
            user=User.objects.get(pk=thread["InsertUserID"]),
            created_on=thread["DateInserted"],
            text=thread["Body"],
        )
        new_post.save()
        new_post.created_on = thread["DateInserted"]
        new_post.save()
        patch("forum-post-%d" % new_post.id, thread["DateInserted"])

        comments = fetch_all(db, "GDN_Comment", DiscussionID=thread["DiscussionID"])
        for comment in comments:
            user = User.objects.get(pk=comment["InsertUserID"])
            new_comment = Comment(
                user=user,
                content_type=ContentType.objects.get_for_model(Post),
                object_pk=new_post.pk,
                comment=comment["Body"],
                site_id=settings.SITE_ID,
                submit_date=comment["DateInserted"],
            )
            new_comment.save()
            patch("comment-%d" % new_comment.id, comment["DateInserted"])
            copied_comments += 1
        copied_posts += 1
        if copied_posts % 10 == 0:
            print "%d posts. %d comments." % (copied_posts, copied_comments)

    print "%d posts. %d comments." % (copied_posts, copied_comments)
开发者ID:Dongjinmedia,项目名称:algospot,代码行数:45,代码来源:fromvanilla.py


注:本文中的django.contrib.comments.models.Comment类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。