article / article / models.py

from datetime import datetime

from django.db import models
from django.contrib.auth.models import User
from django.contrib.comments.models import Comment
from django.forms import ModelForm
from django.db.models.signals import pre_save
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager

import tagging
from tagging.fields import TagField
from tagging.models import Tag

from article.managers import ActiveRecipe, ActivePost, MemberRecipe

class Category(models.Model):
    category_name = models.CharField(max_length=40,unique=True)
    category_date = models.DateTimeField(auto_now_add=True)
    class Meta:
        verbose_name_plural = "Categories"
        ordering = ('category_name',)
	
    def __unicode__(self):
        return self.category_name

class Cookbook(models.Model):
    name = models.CharField(max_length=200)
    affiliate_link = models.URLField(verify_exists=True,null=True,blank=True)

    def __unicode__(self):
        return self.name
		
class Recipe(models.Model):
    FEATURE_TYPES = (
        ('3', 'Sub Featured Photo'),
	('2', 'Featured Photo'),
	('0', 'Not Featured')
    )
    recipe_author = models.ForeignKey(User,verbose_name='Name', default=2) #default Lindsay
    recipe_name = models.CharField(max_length=200,unique=True, db_index=True, verbose_name='Recipe Name')
    recipe_slug = models.SlugField('Recipe URL', max_length=50,unique=True)
    recipe_servings = models.DecimalField(max_digits=4, decimal_places=2, verbose_name='Servings')
    recipe_description = models.TextField(verbose_name='Description')
    recipe_instructions = models.TextField(verbose_name='Instructions')
    recipe_date_create = models.DateField(auto_now_add=True)
    recipe_date_lastmod = models.DateField(auto_now=True)
    recipe_enable_comments = models.BooleanField(default=False)
    prep_time = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    cook_time = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    calories = models.DecimalField(max_digits=6, decimal_places=2,  null=True,blank=True)
    carbohydrates = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    fat = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    fiber = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    protein = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    sugar = models.DecimalField(max_digits=6, decimal_places=2, null=True,blank=True)
    featured_items =  models.CharField("Featured Items", max_length=1, choices=FEATURE_TYPES,default=0,)
    cookbook = models.ForeignKey(Cookbook,null=True,blank=True)
    cookbook_page = models.CharField(max_length=6,null=True,blank=True)
    members_only  = models.BooleanField(default=False)
    is_published = models.BooleanField(
		"Published", default=False, help_text="Publish this recipe?"
	)
    published_on = models.DateTimeField(
		"Date Published", blank=True, null=True,
		help_text="Manually change the date this post was published on."
	)
    rec_tags = TagField()
    sites = models.ManyToManyField(Site)
    objects = models.Manager()
    active = ActiveRecipe()
    members = MemberRecipe()
    on_site = CurrentSiteManager()		
	
    class Meta:
        ordering = ('recipe_name',)

    def __unicode__(self):
        return self.recipe_name

    @models.permalink
    def get_absolute_url(self):
        return ('article.views.recipe_detail',  None, { 'recipe_slug':
                                                        self.recipe_slug })
    def total_time(self):
        return self.prep_time + self.cook_time

    def get_subfeature_photos(self):
        return self.recipephotos_set.filter(type=1)

    def get_small_photos(self):
        return self.recipephotos_set.filter(type=3)

    def get_instruction_photos(self):
        return self.recipephotos_set.filter(type__in=[4,5]).order_by('order')

    def get_ingredients(self):
        return RecipeIngredient.objects.filter(ri_recipe=self.pk)
        
try:
    tagging.register(Recipe)
except tagging.AlreadyRegistered:
    pass

class PostType(models.Model):
    # Article, Blog post, FAQ, Index, etc 
    posttype_name = models.CharField(max_length=40,unique=True)

    def __unicode__(self):
        return self.posttype_name
	
class Post(models.Model):
    post_author = models.ForeignKey(User, default=2) #default Lindsay
    post_date_create = models.DateTimeField(auto_now_add=True,null=True)
    post_date_lastmod = models.DateTimeField(auto_now=True)
    post_content = models.TextField()
    post_title = models.CharField(max_length=200,unique=True)
    post_category = models.ForeignKey(Category, default=1) # default Vegan
    post_excerpt = models.TextField(null=True,blank=True)
    post_type = models.ForeignKey(PostType, default=1) #default Blog
    post_recipe = models.ForeignKey(Recipe,null=True,blank=True)
    post_slug = models.SlugField('Post URL', max_length=50,unique=True)
    post_enable_comments = models.BooleanField(default=1) #Enabled by default
    is_published = models.BooleanField(
		"Published", default=False, help_text="Publish this post?"
	)
    published_on = models.DateTimeField(
		"Date Published", blank=True, null=True,
		help_text="Manually change the date this post was published on.  WARNING: Be careful changing posts that have already been published. You may accidently change the URL."
	)
    post_tags = TagField()
    sites = models.ManyToManyField(Site)
    post_image = models.URLField(max_length=255, null=True, blank=True)
    #Manager objects
    objects = models.Manager()
    active = ActivePost()
    on_site = CurrentSiteManager()
    date_field = "published_on"
    
    class Meta:
        get_latest_by  = "published_on"
	    
    def __unicode__(self):
       return self.post_title

    #permalinks helps create sitemap
    @models.permalink
    def get_absolute_url(self):
        return ('article.views.post_detail', None, {
            'year': self.published_on.strftime("%Y"),
            'month': self.published_on.strftime("%m"),
            'post_slug': self.post_slug })

    def get_tag_list(self):
        return self.post_tags.split(" ")



"""
Save signal for sets a pubdate when the users selects publish but 
does not specify a date.
"""
def pub_date_check(sender, **kwargs):
    obj = kwargs['instance']
    if obj.is_published and obj.published_on is None:
        obj.published_on = datetime.now()

def post_tag_check(sender, **kwargs):
    obj = kwargs['instance']
    if obj.post_tags:
        from string import strip
        obj.post_tags = strip(obj.post_tags)

def recipe_tag_check(sender, **kwargs):
    obj = kwargs['instance']
    if obj.rec_tags:
        from string import strip
        obj.rec_tags = strip(obj.rec_tags)

pre_save.connect(pub_date_check, sender=Post)
pre_save.connect(post_tag_check, sender=Post)
pre_save.connect(pub_date_check, sender=Recipe)
pre_save.connect(recipe_tag_check, sender=Recipe)

try:
    tagging.register(Post)
except tagging.AlreadyRegistered:
    pass


class IngredientType(models.Model):
    #Classifcation of ingredients
    ingred_type_class = models.CharField('Ingred Type', max_length=75,unique=True)
    ingred_type_slug = models.SlugField('Ingred Type URL', max_length=50,unique=True)
    ingred_type_date = models.DateField(auto_now_add=True)
	
    class Meta:
        ordering = ('ingred_type_class',)

    def __unicode__(self):
        return self.ingred_type_class
	
class Ingredient(models.Model):
    #ingredient name example "garlic"
    ingred_name = models.CharField(max_length=100,unique=True, db_index=True)
    ingred_slug = models.SlugField('Ingred URL', max_length=50,unique=True)
    ingred_type = models.ForeignKey(IngredientType)
    ingred_date = models.DateField(auto_now_add=True)
    affiliate_link = models.URLField(verify_exists=True,null=True,blank=True)

    #class Meta:
    #    ordering = ('ingred_name',)

    def __unicode__(self):
        return self.ingred_name	

class Measurement(models.Model):
    MEAS_CHOICES = (
	('S', 'Standard'),
        ('M', 'Metric'),
    )
    m_name = models.CharField("Measurement", max_length=20,unique=True)
    m_std =  models.CharField("Type", max_length=1, choices=MEAS_CHOICES)
    m_date = models.DateField(auto_now_add=True)
	
    class Meta:
        ordering = ('m_name',)

    def __unicode__(self):
        return self.m_name
		
class RecipeIngredient(models.Model):
    #Includes actual ingredient amounts
    ri_recipe = models.ForeignKey(Recipe, related_name="recipe_ingred")
    ri_amount = models.DecimalField(max_digits=8, decimal_places=3,
                                    verbose_name='Amount')
    ri_measurement = models.ForeignKey(Measurement, verbose_name='Measurement',
                                       blank=True, null=True)
    ri_ingred = models.ForeignKey(Ingredient,verbose_name='Ingredient Name')
    ri_optional = models.BooleanField(verbose_name='Optional Ingredient')
    ri_date = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return unicode(self.ri_ingred.ingred_name)

    def get_ingredient_name(self):
        return unicode(self.ri_ingred.ingred_name)

    def get_measurement_name(self):
        if self.ri_measurement:
            return unicode(self.ri_measurement.m_name)
        else:
            return None

    def get_measurement_id(self):
        if self.ri_measurement:
            return unicode(self.ri_measurement.id)
        else:
            return None
        
    ri_amount.short_description = "Amount"
		
class RecipePhotos(models.Model):
    PHOTO_TYPES = (
        ('5', 'Video Slide.'),
	('4', 'Instructions Photo: _x_'),
	('3', 'Sub Featured Photo: 278x209'),
	('2', 'Featured Photo: 605x317'),
	('1', 'Recipe Photo 500x358'),
    )
    recipe = models.ForeignKey(Recipe)
    url = models.URLField(max_length=128,verify_exists=True)
    type =  models.CharField("Type", max_length=1, choices=PHOTO_TYPES)
    pub_date = models.DateField(auto_now_add=True)
    sites = models.ManyToManyField(Site)
    text = models.TextField(null=True, blank=True)
    order = models.IntegerField(null=True, blank=True)
    
    class Meta:
        ordering = ('recipe','order')
        verbose_name_plural = "Recipe Photos"
	
    def __unicode__(self):
        return self.url
		
class UserPhotos(models.Model):
    PHOTO_TYPES = (
	('2', 'Secondary Photo'),
	('1', 'FrontPage Photo'),
    )
    url = models.URLField(max_length=128,verify_exists=True)
    pub_date = models.DateField(auto_now_add=True)
    type =  models.CharField("Type", max_length=1, choices=PHOTO_TYPES, default=1)
    sites = models.ManyToManyField(Site, default='2')
	
    class Meta:
        ordering = ('-pub_date',)
      	verbose_name="User Photos"

    def __unicode__(self):
        return self.url
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.