Ejemplo n.º 1
0
def comment_block(target):
    return {
        'target': target,
        'comment_form': CommentForm(),
        'comment_list': Comment.get_by_target(target),
        'comment_count': Comment.get_by_target(target).count()
    }
Ejemplo n.º 2
0
def details_post(request, slug):
    instance = Post.objects.get(slug=slug)
    comments = instance.get_comment
    print(get_read_time(instance.get_markdown()))
    initial_data = {
        "content_type": instance.get_content_type,
        "object_id": instance.id
    }
    form = CommentForm(initial=initial_data)
    if request.method == "POST":
        form = CommentForm(request.POST or None, initial=initial_data)
        if form.is_valid():
            print('yes')
            c_type = form.cleaned_data.get("content_type")
            print(c_type)
            content_type = ContentType.objects.get(model=c_type)
            print(content_type)
            obj_id = form.cleaned_data.get("object_id")
            print(obj_id)
            content_data = form.cleaned_data.get("content")
            #print(content_data)
            ##replies
            parent_obj = None

            try:
                parent_id = int(request.POST.get("parent_id"))
            except:
                parent_id = None

            if parent_id:
                parent_qs = Comments.objects.filter(id=parent_id)
                if parent_qs.exists():
                    parent_obj = parent_qs.first()
            new_comment, created = Comments.objects.get_or_create(
                user=request.user,
                content_type=content_type,
                object_id=obj_id,
                content=content_data,
                parent=parent_obj,
            )
            return HttpResponseRedirect(
                new_comment.content_object.get_absoulte_url())

    context = {"posts": instance, "comments": comments, "form": form}
    return render(request, 'details.html', context)
Ejemplo n.º 3
0
def comment_thread(request,id):
    obj = Comments.objects.get(id=id)
    try:
        obj = Comments.objects.get(id=id)
    except:
        raise Http404    

    if not obj.is_parent:
        obj = obj.parent

    initial_data = {
        "content_type": obj.content_type,
        "object_id":obj.id
    }
    form = CommentForm(initial=initial_data)
    if request.method =="POST":
        form = CommentForm(request.POST or None,initial=initial_data)
        if form.is_valid():
            c_type = form.cleaned_data.get("content_type")
            content_type = ContentType.objects.get_for_model(obj)
            obj_id = form.cleaned_data.get("object_id")
            content_data = form.cleaned_data.get("content")
            parent_obj = None
            try:
                parent_id  = int(request.POST.get("parent_id"))
            except:
                parent_id = None
            if parent_id:
                parent_qs = Comments.objects.filter(id=parent_id)
                if parent_qs.exists() :
                    parent_obj = parent_qs.first()   
            new_comment,created = Comments.objects.get_or_create(
                                   user = request.user,
                                   content_type=content_type,
                                   object_id= obj_id,
                                   content = content_data,   
                                   parent = parent_obj, 
                                )
                              
            return HttpResponseRedirect(new_comment.content_object.get_absoulte_url())          
    context = {
        "comment":obj,
        'form':form
    }
    return render(request,"comment_thread.html",context)
Ejemplo n.º 4
0
def comment_block(target):
    """自定义评论标签"""
    # 在使用地方添加 {% comment_block request.path %} 使用。request.path为参数传递给comment_block()
    # return给block.html
    return {
        'target': target,
        'comment_form': CommentForm(),
        'comment_list': Comment.get_by_target(target)
    }
Ejemplo n.º 5
0
	def get_context_data(self, **kwargs):
		context = super().get_context_data(**kwargs)
		store = Store.objects.get(id=self.kwargs['pk'])
		food = Food.objects.filter(stores=store).get(id=self.kwargs['food_id'])
		context['food'] = food
		context['cart_food_form'] = CartAddFoodForm()
		context['comment_form'] = CommentForm()
		comments = Comment.objects.filter(food=food)[:5]

		comment_times = []
		now = datetime.now()
		date_format = "%Y-%m-%d  %H:%M:%S"
		time1 = now.strftime("%Y-%m-%d  %H:%M:%S")
		time_now = datetime.strptime(time1,date_format)
		for comment in comments:
			time2 = comment.created.strftime("%Y-%m-%d  %H:%M:%S")
			time_2 = now.strptime(time2,date_format)
			diff_time = time_now - time_2
			if diff_time.days > 0:
				weeks = int(diff_time.days / 7)
				months = int(diff_time.days / 30)
				if months > 0:
					comment_times.append('{} months ago'.format(months))
				else:
					if weeks > 0:
						comment_times.append('{} weeks ago'.format(weeks))
					else:
						comment_times.append('{} days ago'.format(diff_time.days))
			else:
				hours = int(diff_time.seconds / (3600))
				if hours > 0:
					comment_times.append('{} hours ago'.format(hours))
				else:
					minutes = int((diff_time.seconds % 3600) / 60)
					if minutes > 0:
						comment_times.append('{} minutes ago'.format(minutes))
					else:
						comment_times.append('just now')

		food_comments = zip(comments,comment_times)
		context['food_comments'] = food_comments

		self.request.session['store_id'] = store.id

		return context
Ejemplo n.º 6
0
def SubDetail(request, project):
    isactive = 'sub'
    if request.session.get('is_login') == None:
        return render(request, 'LoginWarning.html', locals())
    CTL = GetCTL(request)
    Project_model = models.RequestInfo.objects.get(RequestNumber=project)
    RequestNumber = Project_model.RequestNumber
    RequestType = Project_model.RequestType
    RequestUser = Project_model.RequestUser
    RequestTargetGroup = Project_model.RequestTargetGroup
    RequestUserName = Project_model.RequestUserName
    RequestEmail = Project_model.RequestEmail
    RequestContent = Project_model.RequestContent
    RequestTargetData = Project_model.RequestTargetData
    RequestStatus = Project_model.RequestStatus
    RequestDate = Project_model.RequestDate.strftime('%Y-%m-%d %H:%M')
    comments = Comment.objects.filter(Project=project)
    comment_form = CommentForm()
    return render(request, 'RequstAnswer/subdetail.html', locals())
Ejemplo n.º 7
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        instance = Blog.objects.get(id=self.kwargs['pk'])
        # comments = Comment.objects.filter_by_instance(instance)
        comments = Comment.objects.filter(
            content_type=ContentType.objects.get_for_model(Blog),
            object_id=instance.id)

        comment_form = CommentForm()

        if self.request.user.is_authenticated:
            user_info = UserInfo.objects.filter(user=self.request.user).first()
        else:
            user_info = None

        # if instance.is_series:
        #     self.template_name = 'Blog/blog_detail_series.html'

        # START: Blog正文Markdown
        blog_content = markdown.Markdown(extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
            # 'markdown.extensions.toc',
            TocExtension(slugify=slugify),
        ])
        context['blog_content'] = blog_content.convert(instance.content)
        # 目录
        context['toc'] = blog_content.toc
        # END: Blog正文Markdown

        # 判断这篇文章是否被赞过,如果被赞过,则网页上显示红色按钮;如果没有,则页面上显示白色按钮
        # 如果用户没有登录,则直接显示白色按钮
        if not self.request.user.is_authenticated:
            already_like = False
        # 如果用户已经登录
        else:
            like = Like.objects.filter(
                content_type=ContentType.objects.get_for_model(Blog),
                object_id=instance.id)
            # 首先判断这篇文章是否有赞
            if like.count() != 0:
                # 然后判断当前登录用户是否赞过这篇文章
                try:
                    user_like = like.get(user=self.request.user)
                    if user_like is not None:
                        already_like = True
                    else:
                        already_like = False
                except ObjectDoesNotExist:
                    already_like = False

            # 如果没有赞,则alread_like=False,显示白色按钮
            else:
                already_like = False

        # START: 文章阅读信息统计
        reading_info = ReadingInfo()
        # 获得IP地址
        x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = self.request.META.get('REMOTE_ADDR')
        reading_info.ip = ip
        # 如果用户已经登录,则reading_info中的user为当前登录用户;否则为默认的NotLoginUser
        if self.request.user.is_authenticated:
            reading_info.username = self.request.user.username

        # 如果当前用户已经登录,保存是否点赞信息
        reading_info.did_like = already_like

        # 如果当前用户已经登录,则在reading_info中保存当前用户对该文章的评论数
        if self.request.user.is_authenticated:
            comment = Comment.objects.filter(
                content_type=ContentType.objects.get_for_model(Blog),
                object_id=instance.id,
                user=self.request.user)
            reading_info.user_comment_count = comment.count()

        reading_info.content_type = ContentType.objects.get_for_model(Blog)
        reading_info.object_id = instance.id
        reading_info.blog_name = instance.title
        reading_info.time = timezone.localtime(timezone.now()) + timedelta(
            days=0, hours=8)

        reading_info.save()
        # END: 文章阅读信息统计

        # START: 系列教程
        # 如果文章是系列教程
        category_dict = []
        if instance.is_series:
            is_series = True
            if instance.series_keyword == 'django_blog':
                category_dict = category.django_blog_category
                context['category_name'] = "Django博客教程"
            elif instance.series_keyword == 'postgresql':
                category_dict = category.postgresql_category
                context['category_name'] = "深入浅出PostgreSQL数据库"
            elif instance.series_keyword == 'mac_tips':
                category_dict = category.mac_tips_category
                context['category_name'] = "Mac实用操作技巧"
            elif instance.series_keyword == 'mac_finder':
                category_dict = category.mac_finder_category
                context['category_name'] = "玩转Mac Finder"
            elif instance.series_keyword == 'mac_alfred':
                category_dict = category.mac_alfred_category
                context['category_name'] = "玩转Mac Alfred"
            elif instance.series_keyword == 'vuforia':
                category_dict = category.vuforia_category
                context['category_name'] = "Vuforia AR开发完全指南"
            elif instance.series_keyword == 'japanese':
                category_dict = category.japanese_category
                context['category_name'] = "日本語文法"

            if str(int(instance.series_index) - 1) in category_dict:
                previous_title = category_dict[str(
                    int(instance.series_index) - 1)]
                try:
                    previous_pk = Blog.objects.get(
                        title__icontains=previous_title).pk
                    context['previous_title'] = previous_title
                    context['previous_pk'] = previous_pk
                except ObjectDoesNotExist:
                    pass

            if str(int(instance.series_index) + 1) in category_dict:
                next_title = category_dict[str(int(instance.series_index) + 1)]
                try:
                    next_pk = Blog.objects.get(title__icontains=next_title).pk
                    context['next_title'] = next_title
                    context['next_pk'] = next_pk
                except ObjectDoesNotExist:
                    pass
        else:
            is_series = False
        # END: 系列教程

        # START: 评论
        # 如果用户评论成功,则comment_success为True,否则为False
        # 这样做的目的是为了当用户提交评论成功后,再次返回文章详情页面时要有评论成功的提示
        if 'comment_success' in self.kwargs:
            if self.kwargs['comment_success'] is True:
                comment_success = True
            else:
                comment_success = False
        else:
            comment_success = False
        # END: 评论

        # START: Sidebar目录
        if instance.is_series:
            is_series = True
            if instance.series_keyword == 'django_blog':
                category_dict = category.django_blog_category
                context['category_name'] = "Django博客教程"
            elif instance.series_keyword == 'postgresql':
                category_dict = category.postgresql_category
                context['category_name'] = "深入浅出PostgreSQL数据库"
            elif instance.series_keyword == 'mac_tips':
                category_dict = category.mac_tips_category
                context['category_name'] = "Mac实用操作技巧"
            elif instance.series_keyword == 'mac_finder':
                category_dict = category.mac_finder_category
                context['category_name'] = "玩转Mac Finder"
            elif instance.series_keyword == 'mac_alfred':
                category_dict = category.mac_alfred_category
                context['category_name'] = "玩转Mac Alfred"
            elif instance.series_keyword == 'vuforia':
                category_dict = category.vuforia_category
                context['category_name'] = "Vuforia AR开发完全指南"
            elif instance.series_keyword == 'japanese':
                category_dict = category.japanese_category
                context['category_name'] = "日本語文法"

            # 目录中的blog名称列表
            category_blog_title_list = category_dict.values()
            # category_blog_title_list = category_dict.items()

            # 目录中的blog pk列表
            category_blog_pk_list = []
            for title in category_blog_title_list:
                try:
                    pk = Blog.objects.get(title=title).pk
                except ObjectDoesNotExist:
                    pk = 0

                category_blog_pk_list.append(pk)
            # 将名称和pk组合成一个(title, pk)的列表,方便在模板中使用
            category_blog_title_pk_list = zip(category_blog_title_list,
                                              category_blog_pk_list)
            context[
                'category_blog_title_pk_list'] = category_blog_title_pk_list
        # END: Sidebar目录

        context['comments'] = comments
        context['comment_form'] = comment_form
        context['user_info'] = user_info
        context['already_like'] = already_like
        context['is_series'] = is_series
        context['comment_success'] = comment_success

        return context