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


Python Comment.save方法代码示例

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


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

示例1: comment

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
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,代码行数:32,代码来源:handle_recipe.py

示例2: anon_comment

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
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,代码行数:62,代码来源:comment.py

示例3: get_context_data

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
 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,代码行数:35,代码来源:cbvviews.py

示例4: add_new_note

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
    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,代码行数:27,代码来源:details.py

示例5: import_comments

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
    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,代码行数:62,代码来源:wp2zinnia.py

示例6: post

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
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,代码行数:33,代码来源:comment.py

示例7: submit_comment

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
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,代码行数:30,代码来源:views_post.py

示例8: approve

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
def approve(request, id):
    config = get_object_or_404(Config, pk=id)
    if config.locked:
        error = ("This configuration is locked. Only admins can unlock "
                 "it.")
        return details(request, config.id, error=error)
    old_status = config.status
    message = ''
    if request.method == 'POST':  # If the form has been submitted...
        data = request.POST
        if data.get('approved', False):
            # check if domains and domains requests are null
            if not config.domains.all() and not config.domainrequests.all():
                error = """Can't approve this configuration. There is no
                        correlated domain."""
                return details(request, id, error=error)
            # check if domain names already exist
            for domain in config.domainrequests.all():
                if Domain.objects.filter(name=domain).exclude(
                        Q(config__status='deleted') |
                        Q(config__status='invalid')):
                    error = """Can't approve this configuration. Domain is
                            already used by another approved configuration."""
                    return details(request, id, error=error)
            config.status = 'approved'
            for domain in config.domainrequests.all():
                exists = Domain.objects.filter(name=domain)
                if exists:
                    claimed = exists[0]
                    claimed.config = config
                else:
                    claimed = Domain(name=domain.name,
                                     config=config)
                claimed.save()
                domain.delete()
        elif data.get('denied', False):
            # Check mandatory comment when invalidating
            if data['comment'] == 'Other - invalid':
                if not data['commenttext']:
                    error = "Enter a comment."
                    return details(request, id, error=error)
                message = data['commenttext']
            else:
                message = data['comment']
            config.status = 'invalid'
        else:
            raise ValueError("shouldn't get here")
        config.save()
        comment = Comment(user_name='ISPDB System',
                          site_id=settings.SITE_ID)
        c = "<ul><li><b>Status</b> changed from <b><i>%s</i></b> to \
             <b><i>%s</i></b> by %s</li></ul>\n %s" % (old_status,
            config.status, request.user.email, message)
        comment.comment = c
        comment.content_type = ContentType.objects.get_for_model(Config)
        comment.object_pk = config.pk
        comment.save()

    return HttpResponseRedirect('/details/' + id)  # Redirect after POST
开发者ID:mozilla,项目名称:ispdb,代码行数:61,代码来源:views.py

示例9: testCommentNotifications

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
    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,代码行数:59,代码来源:tests.py

示例10: add

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
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,代码行数:57,代码来源:views.py

示例11: process_doc_from_aries

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
def process_doc_from_aries(go_xml_file, force=False):
    def should_restart_merops(art):
        if force:
            return True
        cutoff_state = State.objects.get(unique_name = 'finish_out')
        most_advanced_arts = art.most_advanced_article_state(same_typesetter=False)
        logger.debug("most_advanced_arts: %s" % most_advanced_arts)
        if most_advanced_arts:
            return (most_advanced_arts.state.progress_index < cutoff_state.progress_index)
        return False

    # add article to AI
    #   extract doi from go.xml
    si_guid = os.path.basename(go_xml_file).split('.go.xml')[0]
    zip_file = os.path.join(os.path.dirname(go_xml_file), si_guid + '.zip')
    doi = PlosDoi(man_e.doi(zip_file)).short
    logger.info("Identified new aries-merops delivery {guid: %s} as %s" % (si_guid,doi))
    celery_logger.info("watch_docs_from_aries identified new file for %s" % doi)

    art, new = Article.objects.get_or_create(doi=doi)
    art.typesetter = Typesetter.objects.get(name='Merops')
    art.si_guid = si_guid

    art.save()

    old_state = art.current_state

    if art.current_state.unique_name == 'new':
        delivery_state = State.objects.get(unique_name='delivered_from_aries')
        art_s = ArticleState(article=art, state=delivery_state)
        make_articlestate_if_new(art_s)

    if should_restart_merops(art):
        # extract manuscript, rename to doi.doc(x)
        logger.info("%s, delivery arrived, extracting manuscript and queueing for initial processing" % art.doi)
        user = get_or_create_user("aries_delivery_watch_bot", first_name="Aries Delivery Watch Robot")
        note = Comment(user=user,
                       content_type=ContentType.objects.get_for_model(Article),
                       object_pk = art.pk,
                       submit_date = datetime.datetime.utcnow().replace(tzinfo=utc),
                       comment = "A new package for this article was just delivered by Aries and AI will automatically attempt to extract a manuscript for Merops initial processing.",
                       site_id = settings.SITE_ID)
        note.save()
        extract_manuscript_from_aries(zip_file, art )
    else:
        # do nothing but write a note indicating there's a new export
        logger.info("%s, delivery arrived, but article in too advanced a state to automatically process, %s" % (art.doi, art.current_state.name))
        user = get_or_create_user("aries_delivery_watch_bot", first_name="Aries Delivery Watch Robot")
        note = Comment(user=user,
                       content_type=ContentType.objects.get_for_model(Article),
                       object_pk = art.pk,
                       submit_date = datetime.datetime.utcnow().replace(tzinfo=utc),
                       comment = "A new package for this article was just delivered by Aries but was not automatically processed.  Please review this package and repull the article if desired.",
                       site_id = settings.SITE_ID)
        note.save()
开发者ID:PLOS-Web,项目名称:AI,代码行数:57,代码来源:merops_tasks.py

示例12: test_comment_post_save

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
 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,代码行数:13,代码来源:tests.py

示例13: do_comments

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
def do_comments(cursor,ID,entry):
    cursor.execute('select comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content from wp_comments where comment_approved=1 and comment_post_ID=%s'%ID)
    comments=cursor.fetchall()
    for comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content in comments:
        comm=Comment(content_object=entry,site=SITE,user_name=unic(comment_author)[:49],user_email=comment_author_email,user_url=comment_author_url,comment=unic(comment_content),ip_address='127.0.0.1',submit_date=comment_date,is_public=True,is_removed=False)
        try: comm.save(force_insert=True)
        except Exception, e:
            print comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content
            print Exception, e
            if 'Incorrect string value' in e:
                comm.comment=comment_content.decode('latin1')
		comm.save(force_insert=True)
开发者ID:ivh,项目名称:TmyCMS,代码行数:14,代码来源:import_wp.py

示例14: test_notify_on_comment

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
 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,代码行数:17,代码来源:tests.py

示例15: import_comments

# 需要导入模块: from django.contrib.comments.models import Comment [as 别名]
# 或者: from django.contrib.comments.models.Comment import save [as 别名]
    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,代码行数:50,代码来源:wp2zinnia.py


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