Source

article / article / views.py

from __future__ import unicode_literals
import re
from datetime import datetime

from django.conf import settings
from django.db.models import Count
from django.shortcuts import render_to_response
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext
from django.views.generic.list_detail import object_list
from django.contrib.sites.models import Site
from django.core import serializers
from django.contrib.sessions.models import Session
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.dates import ArchiveIndexView, MonthArchiveView, YearArchiveView
from django.core.mail import send_mail

from tagging.models import TaggedItem, Tag
from mailsnake import MailSnake

from article.models import Post, Recipe, Ingredient
from article.models import RecipeIngredient, RecipePhotos, UserPhotos
from community.models import UserProfile, Transaction
from article.forms import ContactForm


def main_index(request):
    current_site = Site.objects.get_current()
    sample_recipes = Recipe.active.filter(recipephotos__type=3, 
                                        featured_items=3)[:7]
    posts = Post.active.filter(sites=current_site.id).filter(
                              post_type__in=[1,4]).order_by(
                              '-published_on')[:1]	
    return render_to_response('homepage.html', locals(),
                                  context_instance=RequestContext(request))
'''
class ArchiveViewIndex(ArticleViewAbstractClass, ArchiveIndexView):
    date_field = "published_on"
    current_site = Site.objects.get_current() 
    queryset = Post.active.filter(sites=current_site.id, 
                                   post_type__in=[1,4]).order_by(
                                   '-published_on')
'''
def post_index(request):
    ''' Displays an index of blog and video posts. type_of_posts in only set in
    the post_index and video_index views to change the displayed header text in
    the templates.
    
    default: type_of_posts = 0
    '''
    current_site = Site.objects.get_current() 
    post_list = Post.active.filter(sites=current_site.id, 
                                   post_type__in=[1,4]).order_by(
                                   '-published_on')
    type_of_posts = 0
    paginator = Paginator(post_list, 3) # Show 5 posts per page
	
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
	page = 1
	
    try:
        posts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
	
    return render_to_response('post_list.html', locals(), 
                              context_instance=RequestContext(request))

def post_category_index(request, category):
    ''' Displays an index of blog and video posts. type_of_posts in only set in
    the post_index and video_index views to change the displayed header text in
    the templates.
    
    default: type_of_posts = 0
    '''
    current_site = Site.objects.get_current() 

    try:
        tag_obj = Tag.objects.get(name=category)
        tagged_items = TaggedItem.objects.get_by_model(Post, tag_obj)
        post_list = tagged_items.filter(sites=current_site.id,
                                    is_published=1,published_on__lt=datetime.now(),
                                    post_type__in=[1,4]).order_by('-published_on')
    except (Tag.DoesNotExist, TaggedItem.DoesNotExist, Post.DoesNotExist):
        raise Http404

    type_of_posts = 0
    paginator = Paginator(post_list, 5) # Show 5 posts per page
	
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
	page = 1
	
    try:
        posts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
	
    return render_to_response('category_list.html', locals(), 
                              context_instance=RequestContext(request))

def video_index(request):
    ''' Displays an index of Video only blog posts. type_of_posts in only set in
    the post_index and video_index views to change the displayed header text in
    the templates.

    default video: type_of_posts = 1
    '''
    current_site = Site.objects.get_current()
    post_list = Post.active.filter(sites=current_site.id, 
                                   post_type=4).order_by('-published_on')
    type_of_posts = 1
    paginator = Paginator(post_list, 3) # Show 8 posts per page
	
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
	
    try:
        posts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
	
    return render_to_response('post_list.html', locals(), 
                              context_instance=RequestContext(request))
	
def post_detail(request, year, month, post_slug):
    try:
        current_site = Site.objects.get_current()
        post = Post.active.filter(sites=current_site.id).get(post_slug=post_slug)
        recipephotos = RecipePhotos.objects.filter(sites=current_site.id, 
                                                  type=1,recipe=post.post_recipe,
                                                  recipe__is_published=True)
        previous = Post.active.filter(sites=current_site.id, 
                                     id__lt=post.id).order_by(
                                     '-published_on')[:1]
        next = Post.active.filter(sites=current_site.id, 
                                  id__gt=post.id).order_by('id')[:1]
    except Post.DoesNotExist:
        raise Http404
    return render_to_response('post_detail.html', locals(),
                              context_instance=RequestContext(request))




def recipe_detail(request, recipe_slug):
    '''
    This view will handle all recipe details pages.
    '''
    try:
        current_site = Site.objects.get_current()
        recipe = Recipe.objects.filter(is_published=1, published_on__lt=datetime.now()).get(recipe_slug=recipe_slug)
        recipephotos = RecipePhotos.objects.filter(recipe=recipe,type=1)
    except Recipe.DoesNotExist:
        raise Http404
    return render_to_response('recipe_detail.html', locals(),
                                  context_instance=RequestContext(request))

def recipe_index(request, tag=None):
    def clean_params(reqparams):
        a = reqparams.split('&')
        valid_names = ['qname', 'i1', 'i2', 'i3']
        newlist = []
        # Look for valid tags and values.
        for i in a:
            j = i.split('=')
            if j[0] in valid_names and j[1]:
                newlist.append(j)
        # ReBuild the querystring to be passed for pagination.
        clean = []
        for o in newlist:
            clean.append('='.join(o))
        queryparams = '&' + '&'.join(clean)
        return queryparams

    current_site = Site.objects.get_current()
    sub_featured = Recipe.active.filter(recipephotos__type=3, 
                                        featured_items=3)[:7]

    query_tag = Tag.objects.all() # Need to filter tags by Site
    tags = TaggedItem.objects.get_by_model(Recipe, query_tag)


    qname = request.GET.get('qname')
    ingred1 = request.GET.get('i1')
    # Setting a default empty string prevents passing the query None.
    ingred2 = request.GET.get('i2', default='')
    ingred3 = request.GET.get('i3', default='')
    reqparams = request.META.get('QUERY_STRING')

    if reqparams:
        queryparams = clean_params(reqparams)

    if tag:
        try:
            tag_obj = Tag.objects.get(name=tag)
            recipes_list = TaggedItem.objects.get_by_model(Recipe, tag_obj)
            if not recipes_list:
                errormsg = "No Tag matches <strong>{0}</strong>.".format(tag) 
        except (Tag.DoesNotExist, TaggedItem.DoesNotExist):
            raise Http404
    elif qname:
        try:
            recipes_list = Recipe.active.filter(sites=current_site.id).filter(recipe_name__icontains=qname).order_by('recipe_name')
            if not recipes_list:
                errormsg = "No Recipe Name matches <strong>{0}</strong>.".format(qname)
        except Recipe.DoesNotExist:
            raise Http404
    elif ingred1:
        try:
            recipes_list = Recipe.active.filter(recipe_ingred__ri_ingred__ingred_name__icontains=ingred1).filter(recipe_ingred__ri_ingred__ingred_name__icontains=ingred2).filter(recipe_ingred__ri_ingred__ingred_name__icontains=ingred3).distinct().order_by('recipe_name')
            if not recipes_list:
                errormsg = "<h2>No ingredient matches <strong>{0} {1} {2}</strong></h2>".format(ingred1, ingred2, ingred3)
        except Recipe.DoesNotExist:
            raise Http404
    else:
        recipes_list = Recipe.active.filter(sites=current_site.id).order_by('recipe_name')

    paginator = Paginator(recipes_list, 12) # Show 12 posts per page
	
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
	page = 1
	
    try:
        recipes = paginator.page(page)
    except (EmptyPage, InvalidPage):
        recipes = paginator.page(paginator.num_pages)
	
    return render_to_response('recipe_list.html',
                              locals(),context_instance=RequestContext(request))


def meals(request, name):
    """
    The name is url specifier ie /meals/summer/ will add the 
    summer menu to the users shopping list.
    """
    if name == 'low_carb':
        _list = [75,63,62,24,25]
    elif name == 'summer':
        _list = [118,79,101,17,153]
    elif name == 'fan_faves':
        _list = [41,37,63,75,92]
    elif name == 'gluten_free':
        _list = [37,73,25,52,24]
    elif name == 'soy_free':
        _list = [23,25,118,75,50]

    for value in _list:
        id = "recipe-" + value.__str__()
        request.session[id] = value
    return HttpResponseRedirect("/mylist/")


def recipe_by_tag(request, *args, **kwargs):
    try:
        current_site = Site.objects.get_current()
        tag = request.path_info.split('/')[2]
        query_tag = Tag.objects.get(**kwargs)
        tags = TaggedItem.objects.get_by_model(Recipe, query_tag)
        recipecount = tags.count()
    except Tag.DoesNotExist:
        raise Http404
    return render_to_response('recipe_by_tag.html',
                              locals(),context_instance=RequestContext(request))

	
def faq_index(request):
    current_site = Site.objects.get_current()
    posts = Post.active.filter(sites=current_site.id, 
                               post_type=3).order_by('post_date_create')
    return render_to_response('faq_index.html',
                              {"posts": posts}, 
                              context_instance=RequestContext(request))	


def random(request):
    current_site = Site.objects.get_current()
    random = Post.active.filter(sites=current_site.id).all().order_by('?')[:3]
    return random

def shoplist(request, *args, **kwargs):
    '''
    Retrive the recipes list from the users cookie. Add the recipe ids to 
    mylist. Mylist is used to filter the results into your_shop_list.
    
    '''
    mylist = []
    for k,v in request.session.items():
        if "recipe-" in k:
            mylist.append(v)

    your_cart = Recipe.active.filter(id__in=mylist)

    your_shop_list = RecipeIngredient.objects.select_related().filter(
        ri_recipe__id__in=mylist).order_by(
        'ri_ingred__ingred_type__ingred_type_class')

    return render_to_response('temp.html', locals(), 
                              context_instance=RequestContext(request))


class YearArchiveView(YearArchiveView):
    queryset = Post.objects.all().order_by("-published_on")

    date_field="published_on"
    make_object_list=True

@csrf_exempt
def mc_signup(request):
    '''
    OAuth enhancement: http://apidocs.mailchimp.com/oauth2/
    API Docs: http://apidocs.mailchimp.com/api/rtfm/

    Exceptions http://apidocs.mailchimp.com/api/1.3/exceptions.field.php
    '''

    if request.method == 'POST':
        post = request.POST

        mc_id = settings.MC_LISTS

        ms = MailSnake(settings.MAILCHIMP_API_KEY)
        if ms.ping():
            for i in mc_id.keys():
                try: 
                    post[i]
                except KeyError:
                    continue
                if post.get('EMAIL') and re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", post.get('EMAIL')) != None:
                    result = ms.listSubscribe(id=mc_id[i], email_address=post.get('EMAIL'))
                else:
                    return HttpResponse("Please enter a real email address.")
            return HttpResponse("<div class='alert-message success'><a onclick=\"$('.alert-message').hide();\" class='close'>x</a><p><strong>Well done!</strong> To complete the subscription process, please click the link in the email we just sent you.</p></div>")
        else:
            return HttpResponse("Our email provider is current experience technical difficulties.")

    else:
        return HttpResponse("Your request is not valid for MailChimp signup.")

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST) 
        if form.is_valid():
            send_mail('Contact Form email from {0}'.format(request.POST['name']), request.POST['message'], request.POST['email'], ['lindsay@happyherbivore.com'], fail_silently=False)
            success = True
    else:
        form = ContactForm()

    return render_to_response('contact.html', locals(), context_instance=RequestContext(request))