當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Comment類代碼示例

本文整理匯總了Python中comments.models.Comment的典型用法代碼示例。如果您正苦於以下問題:Python Comment類的具體用法?Python Comment怎麽用?Python Comment使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Comment類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: handle

    def handle(self, *args, **kwargs):
    	"""
        users = list(User.objects.all())
        for i in range(100):
            q = Event()
            q.author = random.choice(users)
            q.title = u'title {}'.format(i)
            q.text = u'text {}'.format(i)
            q.is_published = True
            q.save()

        print "completed"
        """
        users = list(User.objects.all())
        b = []
        p = []
        c = []
        for _ in range(10):
            b.append(Blog.objects.create())
        for i in range(100):
            t = Event(author=random.choice(users), title = u'title {}'.format(i),
                     text = u'text {}'.format(i), is_published = True,
                     blog=random.choice(b))
            p.append(t)
            t.save()
            Tag.objects.create(name='tag{}'.format(i))
            # TODO tags.add(tag)
        for i in range(1000):
            com = Comment(author = random.choice(users), event = random.choice(p),
                           text=u'text {}'.format(i))
            c.append(com)
            com.save()
        print "completed"
開發者ID:PotapovaSofia,項目名稱:stackoverflow,代碼行數:33,代碼來源:db_fill.py

示例2: sync_comment

	def sync_comment(self):
		comments_map = {}
		root_header = None
		root_comment = None

		for comment in self.comments():
			dot()
			if root_header is None or root_header.object_id != comment.nid:
				root_comment = Comment.objects.get_or_create_root_comment(self.node_ctype, comment.nid)[0]
			update_comments_header(Comment, instance=root_comment)
			filters = self.formats_filtering.get(comment.format, self.formats_filtering[1])
			filtered_comment = self.call_filters(comment.comment, filters)
			time_created = timestamp_to_time(comment.timestamp)
			comment_instance = Comment(
				parent_id=comments_map[comment.pid] if comment.pid else root_comment.id,
				object_id=comment.nid,
				content_type=self.node_ctype,
				subject=comment.subject,
				created=time_created,
				updated=time_created,
				user_id=self.users_map.get(comment.uid),
				user_name=comment.name,
				is_public=True,
				is_locked=root_comment.is_locked,
				original_comment=TextVal(self.filter_formats.get(comment.format, 'raw') + ':' + comment.comment),
			)
			comment_instance.save()
			Comment.objects.filter(pk=comment_instance.pk).update(filtered_comment=filtered_comment)
			comments_map[comment.cid] = comment_instance.pk
開發者ID:LinuxOSsk,項目名稱:Shakal-NG,代碼行數:29,代碼來源:import_blackhole.py

示例3: migrate_comments

    def migrate_comments(self):

        for legacy_comment in LegacyComment.objects.all():
            assert isinstance(legacy_comment, LegacyComment)

            date_naive = datetime.utcfromtimestamp(legacy_comment.timestamp)
            date = timezone.make_aware(date_naive, timezone.utc)

            comment = Comment()
            comment.body = legacy_comment.comment
            comment.created = date
            comment.public = not legacy_comment.officer

            comment.user_id = legacy_comment.poster_id  # this is erroring

            if legacy_comment.section == 0:
                continue
            if legacy_comment.section == 1:
                continue
            if legacy_comment.section == 2:
                continue
            if legacy_comment.section == 5:
                continue

            comment.content_type_id = {  # i dont know what the keys are for the different content types
                0: 1,  # user manager
                1: 2,  # application
                2: 3,  # fodder vote
                3: 4,  # quote
                4: 5,  # screenshot
                5: 6   # leadership application
            }.get(legacy_comment.section)

            comment.object_id = legacy_comment.reference
            comment.save()
開發者ID:pombredanne,項目名稱:django-adt,代碼行數:35,代碼來源:migratecomments.py

示例4: tutorial_api

def tutorial_api(request):
    if request.method == "POST":
        print(request.body)
        _body = json.loads(request.body)
        try:
            new_comment = Comment(author=_body["author"], comment=_body["comment"])
            new_comment.save()
        except Exception as e:
            print(e)
    rtn_list = json_encoder.serialize_to_json(Comment.objects.all().values())
    return HttpResponse(rtn_list, content_type="application/json")
開發者ID:tekton,項目名稱:django_react,代碼行數:11,代碼來源:views.py

示例5: delete

    def delete(cls, collection_id):
        collection = cls.objects.get_or_404(id=collection_id)
        if collection.owner != g.user:
            raise Forbidden('Only collection owner can delete collection') if collection.public else NotFound()

        Comment.delete_from_collection(collection)
        Item.delete_from_collection(collection)

        logger.info('Deleting {} ...'.format(collection))
        super(cls, collection).delete()
        logger.info('Deleting {} done'.format(collection))
開發者ID:blstream,項目名稱:myHoard_Python,代碼行數:11,代碼來源:models.py

示例6: test_delete_comment

 def test_delete_comment(self):
     sound = Sound.objects.get(id=19)
     user = User.objects.get(id=2)
     current_num_comments = sound.num_comments
     comment = Comment(content_object=sound,
                       user=user,
                       comment="Test comment")
     sound.add_comment(comment)
     comment.delete()
     sound = Sound.objects.get(id=19)
     self.assertEqual(current_num_comments, sound.num_comments)
     self.assertEqual(sound.is_index_dirty, True)
開發者ID:giuband,項目名稱:freesound,代碼行數:12,代碼來源:tests.py

示例7: new_comment

def new_comment(request):
    # saving the poted comment
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment()
            comment.book = form.cleaned_data.get("book")
            comment.chapter = form.cleaned_data.get("chapter")
            comment.example = form.cleaned_data.get("example")
            comment.page = form.cleaned_data.get("page")
            comment.title = form.cleaned_data.get("title")
            comment.body = form.cleaned_data.get("body")
            comment.email = form.cleaned_data.get("email", "Anonymous")
            comment.save()
            return HttpResponseRedirect(
                '/comments/get/?book={0}&chapter={1}&example={2}&page={3}'.format(
                    comment.book, comment.chapter, comment.example, comment.page
                )
            )
        else:
            book = request.POST.get('book', '')
            chapter = request.POST.get('chapter', '')
            example = request.POST.get('example', '')
            page = request.POST.get('page', '')
            return HttpResponseRedirect(
                '/comments/new/?book={0}&chapter={1}&example={2}&page={3}'.format(
                    book, chapter, example, page
                )
            )

    # retriving comment parameters
    book = request.GET.get('book', '')
    chapter = request.GET.get('chapter', '')
    example = request.GET.get('example', '')
    page = request.GET.get('page', '')
    initial_values = {
        'book': book,
        'chapter': chapter,
        'example': example,
        'page': page
    }
    form = CommentForm(initial = initial_values)
    context = {
        'form': form,
        'book': book,
        'chapter': chapter,
        'example': example,
        'page': page
    }
    context.update(csrf(request))
    return render(request, 'comments/new_comment.html', context)
開發者ID:FOSSEE,項目名稱:Python-TBC-Interface,代碼行數:51,代碼來源:views.py

示例8: comment_app

def comment_app(request):
    if request.method == 'POST':
        c_author = request.POST['author']
        c_email = request.POST['email']
        c_url = request.POST['url']
        c_content = request.POST['content']
        c_obj_class = request.POST['obj_class']
        try:
            c_obj_id = int(request.POST['obj_id'])
        except ValueError:
            raise Http404()
        p = Comment(author=c_author, email=c_email, url=c_url, content=c_content, objclass=c_obj_class, objid=c_obj_id)
        p.save()
    return HttpResponse("評論成功,請返回並刷新頁麵。")
開發者ID:Tian-Yu,項目名稱:Django-myblog,代碼行數:14,代碼來源:views.py

示例9: add

def add(request):
    print "Hit add request for comment"
    r = '/'
    if request.method =='POST':
        form = CommentForm(request.POST)
        #print repr(form.cleaned_data)
        #print request.POST
        if form.is_valid():
            d = form.cleaned_data
            #print d['suid']
            if suid_store.check(d['suid']):
                suid_store.add(d['suid'])
                suid_store.trim()
                c = Comment()
                p = d['parent'].split(':')
                pt = Ticket
                r = '/tickets/'
                print p[0]
                if p[0] in ('ticket','Ticket'):
                    pt = Ticket
                    r = '/tickets/'
                elif p[0] in ('comment','com','Comment','comments','Comments'):
                    pt = Comment
                    r = '/comments/'
                #print r
                #Insert other comment parents here
                try:
                    p = pt.objects.get(id=int(p[1]))
                    #print "Got model of type " + str(type(pt))
                    r += str(p.id) + '/'
                except:
                    #print 'Cannot get model of type ' + str(type(pt))
                    return HttpResponse('Invalid Parent')
                #c.content_type = ContentType.objects.get_for_model(pt)
                c.parent = p
                c.submittedby = request.user.member
                c.submittedtime = datetime.datetime.now()
                c.content = d['content']

                c.save()
                #print d['files']
                fs = getfilesfromfields(d['files'],d['autofiles'])
                if fs:
                    print fs
                    c.attachedfiles.add(*fs)
                c.save()
                
                #print "Id for new comment", c.id
                #print r
            else:
                print "Suid seen before"
        else:
            print "Form is invalid"
        #print r
        return HttpResponseRedirect(r)
開發者ID:hungrygeek,項目名稱:django_python,代碼行數:55,代碼來源:views.py

示例10: get_all_tags

    def get_all_tags(cls, assessment, json_encode=True):
        root = SummaryText.objects.get(title='assessment-{pk}'.format(pk=assessment.pk))
        tags = SummaryText.dump_bulk(root)

        if root.assessment.comment_settings.public_comments:
            descendants=root.get_descendants()
            obj_type = Comment.get_content_object_type('summary_text')
            comments=Comment.objects.filter(content_type=obj_type,
                                            object_id__in=descendants)
            tags[0]['data']['comments'] = Comment.get_jsons(comments, json_encode=False)

        if json_encode:
            return json.dumps(tags, cls=HAWCDjangoJSONEncoder)
        else:
            return tags
開發者ID:ashyhanov,項目名稱:hawc,代碼行數:15,代碼來源:models.py

示例11: test_user_can_delete_comments

 def test_user_can_delete_comments(self):
     self.assertTrue(self.login)
     resource = self.create_resources()
     comment = Comment(
         id=200,
         author=self.user,
         resource=resource,
         content="Test comment"
     )
     comment.save()
     response = self.client.delete(
         '/comment/200',
         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, "success")
開發者ID:andela-ooshodi,項目名稱:codango-debug,代碼行數:15,代碼來源:test_views.py

示例12: testReportComment

    def testReportComment(self):
        # Try to view form anonymously
        # (but get redirected because not authenticated)
        url = reverse('report_comment', args=[self.comment.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)

        # Log in
        self.client.login(username=self.eusa_staff.username, password="")

        # View form
        url = reverse('report_comment', args=[self.comment.id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertIn('form', response.context)
        self.assertIn('comment', response.context)
        self.assertEqual(self.comment, response.context['comment'])

        # Report
        post = {'reason': 'Unacceptable'}
        response = self.client.post(url, post)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(Report.objects.filter(
            content_type=Comment.get_content_type(),
            object_id=self.comment.id))
開發者ID:HughMcGrade,項目名稱:eusay,代碼行數:25,代碼來源:tests.py

示例13: test_user_can_edit_comments

 def test_user_can_edit_comments(self):
     self.assertTrue(self.login)
     resource = self.create_resources()
     comment = Comment(
         id=200,
         author=self.user,
         resource=resource,
         content="Test comment"
     )
     comment.save()
     json_data = json.dumps({'content': 'Another Content', })
     response = self.client.put(
         '/comment/200', json_data, content_type='application/json',
         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, "success")
開發者ID:andela-ooshodi,項目名稱:codango-debug,代碼行數:16,代碼來源:test_views.py

示例14: post

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return Response(status.HTTP_401_UNAUTHORIZED)

        ct = ContentType.objects.get_for_model(MODELS_MAPPINGS[kwargs['model']])

        try:
            obj = ct.get_object_for_this_type(pk=kwargs['object_id'])
        except ObjectDoesNotExist:
            raise ErrorResponse(status.HTTP_404_NOT_FOUND)

        form = CommentForm(request.POST)
        if not form.is_valid():
            raise ErrorResponse(status.HTTP_400_BAD_REQUEST)

        data = {
            'content_type': ct,
            'object_id': kwargs['object_id'],
            'user': request.user,
            'created': datetime.datetime.now(),
            'content': form.cleaned_data['content'],
        }

        parent = form.cleaned_data['parent']
        if parent:
            instance = parent.add_child(**data)
        else:
            instance = Comment.add_root(**data)

        if request.is_ajax():
            return Response(status.HTTP_201_CREATED)
        return HttpResponseRedirect(obj.get_absolute_url())
開發者ID:svartalf,項目名稱:abakron,代碼行數:32,代碼來源:api.py

示例15: render_comment_list

def render_comment_list(context, obj):
    return {
        'qs': Comment.get_for_object(obj),
        'content_type': ContentType.objects.get_for_model(obj),
        'obj': obj,
        'perms': context['perms'],
        'user': context['user']
    }
開發者ID:narqo,項目名稱:djbookru,代碼行數:8,代碼來源:comments_tags.py


注:本文中的comments.models.Comment類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。