def blog_tag(request, slug):
    tag = get_object_or_404(Tags, slug=slug)
    blog_posts = Post.objects.filter(tags__in=[tag], status="P").order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    if "page" in request.GET:
        if not request.GET.get('page').isdigit():
            raise Http404
        page = int(request.GET.get('page'))
    else:
        page = 1
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))
    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    return render(request, 'site/blog/index.html', {'current_page': page, 'tag': tag,
                                                    'last_page': no_pages, 'posts': blog_posts, 'csrf_token': c['csrf_token']}) @login_required
def admin_post_list(request):
    users = User.objects.all()
    blog_posts = Post.objects.all().order_by(
        '-created_on').select_related("user", "category").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    if request.method == "POST":
        if request.user.is_site_admin:
            blog_post = get_object_or_404(Post, id=request.POST.get("blog_id"))
            user = get_object_or_404(
                User, id=request.POST.get("change_author"))
            blog_post.user = user
            blog_post.save()
    return render(request, 'admin/blog/blog-posts.html', {'blog_posts': blog_posts, "users": users}) @login_required
def new_post(request):
    BlogSlugFormSet = inlineformset_factory(Post, Post_Slugs,
                                            can_delete=True, extra=3, fields=('slug', 'is_active'),
                                            formset=CustomBlogSlugInlineFormSet
                                            )
    if request.method == 'POST':
        blog_form = BlogpostForm(request.POST)
        blogslugs_formset = BlogSlugFormSet(request.POST)
        if blog_form.is_valid() and blogslugs_formset.is_valid():
            blog_post = blog_form.save(commit=False)
            blogslugs_formset = BlogSlugFormSet(
                request.POST, instance=blog_post)
            if blogslugs_formset.is_valid():
                blog_post.user = request.user
                if request.POST.get('meta_description'):
                    blog_post.meta_description = request.POST[
                        'meta_description']
                blog_post.status = 'D'
                if request.POST.get('status') == "P":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'P'
                        if not blog_post.published_on:
                            blog_post.published_on = datetime.datetime.now(
                            ).date()

                elif request.POST.get('status') == "T":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'T'

                elif request.POST.get('status') == "R":
                    blog_post.status = 'R'

                blog_post.save()
                blogslugs_formset.save()
                # If no slugs are specified, then create one using title.
                if not blog_post.slugs.all():
                    blog_post.create_blog_slug([slugify(blog_post.title)])
                blog_post.check_and_activate_slug()

                if request.POST.get('tags', ''):
                    tags = request.POST.get('tags')
                    tags = tags.split(',')
                    for tag in tags:
                        blog_tag = Tags.objects.filter(name=tag)
                        if blog_tag:
                            blog_tag = blog_tag[0]
                        else:
                            blog_tag = Tags.objects.create(name=tag)
                        blog_post.tags.add(blog_tag)

                sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD)
                sending_msg = sendgrid.Mail()
                sending_msg.set_subject("New blog post has been created")

                blog_url = 'https://www.micropyramid.com/blog/' + \
                    str(blog_post.slug) + '/'
                message = '<p>New blog post has been created by ' + str(request.user) + ' with the name ' + str(
                    blog_post.title) + ' in the category ' + str(blog_post.category.name) + '.</p>'

                sending_msg.set_html(message)
                sending_msg.set_text('New blog post has been created')
                sending_msg.set_from(request.user.email)
                sending_msg.add_to(
                    [user.email for user in User.objects.filter(is_admin=True)])
                sg.send(sending_msg)

                # cache._cache.flush_all()
                return redirect(reverse('admin_post_list'))
    else:
        blog_form = BlogpostForm()
        blogslugs_formset = BlogSlugFormSet(instance=Post())

    categories = Category.objects.all()
    c = {}
    c.update(csrf(request))
    return render(request, 'admin/blog/blog-new.html',
                  {'categories': categories, 'csrf_token': c['csrf_token'],
                   'blogslugs_formset': blogslugs_formset, 'blog_form': blog_form}
                  ) @login_required
def edit_blog_post(request, blog_slug):
    blog_post = get_object_or_404(Post, slugs__slug=blog_slug)
    active_slug = blog_post.slug
    old_blog_status = blog_post.status
    if active_slug != blog_slug:
        return redirect(reverse('edit_blog_post',
                                kwargs={'blog_slug': active_slug})
                        )
    if not blog_post.is_editable_by(request.user):
        return render_to_response('admin/accessdenied.html')

    BlogSlugFormSet = inlineformset_factory(Post, Post_Slugs,
                                            can_delete=True, extra=3, fields=('slug', 'is_active'),
                                            formset=CustomBlogSlugInlineFormSet
                                            )
    if request.method == 'POST':
        blog_form = BlogpostForm(request.POST, instance=blog_post)
        blogslugs_formset = BlogSlugFormSet(request.POST, instance=blog_post)
        if blog_form.is_valid() and blogslugs_formset.is_valid():
            blog_post = blog_form.save(commit=False)
            if blogslugs_formset.is_valid():
                blog_post.status = old_blog_status
                blog_post.meta_description = request.POST.get(
                    'meta_description')
                if request.POST.get('status') == "P":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'P'
                elif request.POST.get('status') == "T":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'T'
                elif (request.POST.get('status') == "R" or
                      request.POST.get('status') == "D"
                      ):
                    blog_post.status = request.POST.get('status')
                else:
                    pass

                blog_post.save()
                blogslugs_formset.save()
                # If no slugs are specified, then create one using title.
                if not blog_post.slugs.all():
                    blog_post.create_blog_slug([slugify(blog_post.title)])
                blog_post.check_and_activate_slug()

                blog_post.tags.clear()
                if request.POST.get('tags', ''):
                    for tag in blog_post.tags.all():
                        blog_post.tags.remove(tag)
                    tags = request.POST.get('tags')
                    tags = tags.split(',')
                    for tag in tags:
                        blog_tag = Tags.objects.filter(name=tag)
                        if blog_tag:
                            blog_tag = blog_tag[0]
                        else:
                            blog_tag = Tags.objects.create(name=tag)

                        blog_post.tags.add(blog_tag)
                # cache._cache.flush_all()
                return redirect(reverse('admin_post_list'))
    else:
        blog_form = BlogpostForm(instance=blog_post)
        blogslugs_formset = BlogSlugFormSet(instance=blog_post)

    categories = Category.objects.all()
    c = {}
    c.update(csrf(request))
    return render(request, 'admin/blog/blog-edit.html', {'blog_post': blog_post,
                                                         'categories': categories, 'csrf_token': c['csrf_token'],
                                                         'blogslugs_formset': blogslugs_formset, 'blog_form': blog_form}
                  ) @login_required
def admin_category_list(request):
    blog_categories = Category.objects.all().order_by('id')
    return render(request, 'admin/blog/blog-category-list.html', {'blog_categories': blog_categories}) @login_required
def new_blog_category(request):
    if request.method == 'POST':
        validate_blogcategory = BlogCategoryForm(request.POST)
        if validate_blogcategory.is_valid():
            validate_blogcategory.save()

            # cache._cache.flush_all()
            data = {'error': False, 'response': 'Blog category created'}
        else:
            data = {'error': True, 'response': validate_blogcategory.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    if request.user.is_superuser:
        c = {}
        c.update(csrf(request))
        return render(request, 'admin/blog/blog-category.html', {'csrf_token': c['csrf_token']})
    else:
        return render_to_response('admin/accessdenied.html') def blog_category(request, **kwargs):
    page = 1
    slug = kwargs['slug']

    if 'page' in request.GET.keys():
        if request.GET.get('page'):
            return redirect(reverse('blog_category', kwargs={'slug': slug, 'page_num': request.GET.get('page')}))
        else:
            return redirect(reverse('blog_category', kwargs={'slug': slug}))

    if 'page_num' in kwargs:
        page = int(kwargs['page_num'])

        if page == 1:
            return redirect(reverse('blog_category', kwargs={'slug': slug}))

    slug = slug.lower()
    category = get_object_or_404(Category, slug=slug)
    blog_posts = Post.objects.filter(category=category, status="P").order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))

    try:
        if int(page) < 0 or int(page) > (no_pages):
            page = 1
            return HttpResponseRedirect(reverse('blog_category', kwargs={'slug': slug}))
        else:
            page = int(page)
    except:
        page = 1

    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count(
    page, no_pages)

    return render(request, 'site/blog/index.html', {'current_page': page, 'category': category, 'last_page': no_pages,
                                                    'posts': blog_posts, 'csrf_token': c['csrf_token'], 'slug': slug,
                                                    'prev_page': prev_page, 'previous_page': previous_page,
                                                    'aft_page': aft_page, 'after_page': after_page}) def blog_article(request, slug):
    if request.path != request.path.lower():
        return redirect(request.path.lower(), permanent=True)

    blog_post = get_object_or_404(Post, slugs__slug=slug)
    active_slug = blog_post.slug
    if active_slug != slug:
        return redirect(reverse('blog_article',
                                kwargs={'slug': active_slug})
                        )
    if not blog_post.status == 'P':
        if not request.user.is_authenticated():
            raise Http404

    all_blog_posts = list(
        Post.objects.filter(status='P').order_by('-published_on'))
    prev_url = ''
    next_url = ''
    for post in all_blog_posts:
        if str(slug) == str(post.slug):
            try:
                current_index = all_blog_posts.index(post)
                next_que = all_blog_posts[current_index + 1]
                next_url = '/blog/' + str(next_que.slug) + '/'
            except:
                next_url = ''
            try:
                current_index = all_blog_posts.index(post)
                prev_que = all_blog_posts[current_index - 1]
                if current_index == 0:
                    prev_url = ''
                else:
                    prev_url = '/blog/' + str(prev_que.slug) + '/'
            except:
                prev_url = ''
            break
    related_posts = Post.objects.filter(
        category=blog_post.category, status='P').exclude(id=blog_post.id).order_by('?')[:3]
    minified_url = ''
    if 'HTTP_HOST' in request.META.keys():
        try:
            minified_url = google_mini('https://' + request.META['HTTP_HOST'] + reverse(
                'blog_article', kwargs={'slug': slug}), settings.GGL_URL_API_KEY)
        except:
            minified_url = 'https://' + \
                request.META[
                    'HTTP_HOST'] + reverse('blog_article', kwargs={'slug': slug})
    c = {}
    c.update(csrf(request))
    return render(request, 'site/blog/article.html', {'csrf_token': c['csrf_token'], 'related_posts': related_posts,
                                                      'post': blog_post, 'minified_url': minified_url, 'prev_url': prev_url, 'next_url': next_url}) def archive_posts(request, year, month):
    blog_posts = Post.objects.filter(status="P", published_on__year=year, published_on__month=month).order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))

    try:
        if int(request.GET.get('page')) < 0 or int(request.GET.get('page')) > (no_pages):
            page = 1
            return HttpResponseRedirect(reverse('archive_posts'), kwargs={'year': blog_posts[0].published_on.year, 'month': blog_posts[0].published_on.month})
        else:
            page = int(request.GET.get('page'))
    except:
        page = 1

    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count(
    page, no_pages)

    return render(request, 'site/blog/index.html', {'current_page': page, 'year': year, 'month': month, 'last_page': no_pages,
                                                    'posts': blog_posts, 'csrf_token': c['csrf_token'],
                                                    'prev_page': prev_page, 'previous_page': previous_page,
                                                    'aft_page': aft_page, 'after_page': after_page}) @login_required
def delete_category(request, category_slug):
    category = get_object_or_404(Category, slug=category_slug)
    if request.user.is_superuser:
        category.delete()

        # cache._cache.flush_all()
        return HttpResponseRedirect('/blog/category-list/')
    else:
        return render_to_response('admin/accessdenied.html') @login_required
def edit_category(request, category_slug):
    blog_category = get_object_or_404(Category, slug=category_slug)
    if request.method == 'POST':
        validate_blogcategory = BlogCategoryForm(
            request.POST, instance=blog_category)
        if validate_blogcategory.is_valid():
            validate_blogcategory.save()

            # cache._cache.flush_all()
            data = {'error': False, 'response': 'Blog category updated'}
        else:
            data = {'error': True, 'response': validate_blogcategory.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    if request.user.is_superuser:
        c = {}
        c.update(csrf(request))
        return render(request, 'admin/blog/blog-category-edit.html', {'blog_category': blog_category, 'csrf_token': c['csrf_token']})
    else:
        return render_to_response('admin/accessdenied.html') @login_required
def change_category_status(request, category_slug):
    category = get_object_or_404(Category, slug=category_slug)
    if category.is_display:
        category.is_display = False
    else:
        category.is_display = True
    category.save()
    return HttpResponseRedirect('/blog/category-list/')
from django.conf.urls import url
from micro_blog.views import (blog_tag, admin_post_list, new_post, edit_blog_post,
                              admin_category_list, new_blog_category, blog_category,
                              blog_article, archive_posts, delete_category,
                              edit_category, change_category_status)


urlpatterns = [
    url(r'^tag/(?P<slug>[-\w]+)/$', blog_tag),
    url(r'^list/$', admin_post_list, name='admin_post_list'),
    url(r'^new-post/$', new_post, name='new_post'),
    url(r'^edit-post/(?P<blog_slug>[-\w]+)/$', edit_blog_post, name='edit_blog_post'),
    url(r'^category-list/$', admin_category_list, name='admin_category_list'),
    url(r'^new-category/$', new_blog_category, name='new_blog_category'),

    url(r'^(?P<slug>[-\w]+)/$', blog_article, name='blog_article'),