本文整理汇总了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"
示例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
示例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()
示例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")
示例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))
示例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)
示例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)
示例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("评论成功,请返回并刷新页面。")
示例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)
示例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
示例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")
示例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))
示例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")
示例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())
示例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']
}