class Entry(models.Model): """ A challenge submission entry. """ name = models.CharField(max_length=100) email = models.EmailField(max_length=100) user = models.ForeignKey(User, blank=True, null=True) description = models.TextField(blank=True, null=True) screenshot = models.ImageField(upload_to='submission/screenshots') file = models.FileField(upload_to='submission/entries', blank=True, null=True) url = models.URLField(blank=True, null=True) rules = models.BooleanField(default=False) approved = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) userrating = RatingField(range=5, can_change_vote=True) judgerating = RatingField(range=5, can_change_vote=True) class Meta: ordering = ['id'] verbose_name = _('Entry') verbose_name_plural = _('Entries') def __unicode__(self): return '%s from %s' % (self.id, self.name) @models.permalink def get_absolute_url(self): return ('submission.views.detail', None, { 'id': self.id, }) @models.permalink def get_approval_url(self): return ('submission.views.approve', None, { 'id': self.id, }) def filename(self): return os.path.basename(self.file.name) def thumbnail_url(self): return '%s_tn.png' % (self.screenshot.url[:-4]) def overall_judgerating(self): return self.judgerating.get_rating() overall_judgerating.short_description = 'Judge Rating' def overall_publicrating(self): return self.userrating.get_rating() overall_publicrating.short_description = 'Public Rating'
class Game(models.Model): LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( (LIVE_STATUS, 'Live'), (DRAFT_STATUS, 'Draft'), (HIDDEN_STATUS, 'Hidden'), ) status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT_STATUS) title = models.CharField(max_length=130) #creator = models.ForeignKey(User,null=True,blank=True) pub_date = models.DateTimeField('date created',auto_now=False, auto_now_add=True) modified_date = models.DateTimeField('date created',auto_now=True, auto_now_add=False) short_description = models.CharField('Short teaser',max_length=130,help_text='Example: This is an erotic rythm game. Do not miss this') long_description = models.TextField('description',help_text='Example: it is a game about ... and it is great because of ... you should try it out. (if you would want to write the story of your life then this is the place)') short_credits = models.TextField('credits',blank=True,null=True,help_text='Example: It was made by Tim Garbos and Julie Heyde. Thanks to Patrick for the moaning sound effects') video = models.URLField(help_text='Optional video (youtube, vimeo, etc) link',null=True,blank=True) twitter = models.CharField('twitter id',max_length=100,blank=True) developer_url = models.URLField(null=True,blank=True) facebook_page = models.URLField(null=True,blank=True) email = models.EmailField(null=True,blank=True) users = models.ManyToManyField(User,null=True,blank=True) tags = TaggableManager(blank=True) categories = models.ManyToManyField(GameCategory,null=True,blank=True) platforms = models.ManyToManyField(GamePlatform, through='GamePlatformLink',null=True,blank=True) rating_fun = RatingField(range=5,allow_anonymous=True) rating_novelty = RatingField(range=5,allow_anonymous=True) rating_humour = RatingField(range=5,allow_anonymous=True) rating_visuals = RatingField(range=5,allow_anonymous=True) rating_audio = RatingField(range=5,allow_anonymous=True) jam = models.ForeignKey(GameJam,null=True,blank=True) def __unicode__(self): return self.title class Meta: verbose_name_plural = "games" @classmethod def create(cls, title): game = cls(title=title) # add default links return game
class Worksheet(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) manager = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='+') # contrib title = models.CharField(max_length=200) titleTag = models.CharField(max_length=70, blank=True) chapters = models.ManyToManyField(Chapter) # contrib description = HTMLField() # attachments: contrib files = models.ManyToManyField(File, blank=True) timeCreated = models.DateTimeField(editable=False) timeModified = models.DateTimeField(editable=False) userModified = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='+') rating = RatingField(range=5, allow_anonymous=True) publish = models.BooleanField(default=False) def __unicode__(self): return self.title def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.timeCreated = datetime.datetime.today() self.timeModified = datetime.datetime.today() super(Worksheet, self).save(*args, **kwargs)
class Note(models.Model): column = models.ForeignKey(Column, null=True, blank=True) row = models.ForeignKey(Row, null=True, blank=True) debate = models.ForeignKey(Debate, null=True, blank=True) title = models.CharField(_('Title'), max_length=60, blank=True, null=True) message = models.TextField(_('Message'), max_length=100, null=True, blank=True) author = models.ForeignKey(User, null=True, blank=True, related_name="note_author") last_mod_author = models.ForeignKey(User, null=True, blank=True, related_name="update_author") date = models.DateTimeField(_('Created on'), auto_now_add=True) last_mod = models.DateTimeField(_('Last modified'), auto_now=True) rating = RatingField(range=3, can_change_vote=False, allow_anonymous=False, allow_delete=False, use_cookies=False) comment_count = models.IntegerField(null=True, blank=True) def __unicode__(self): return self.message
class Photo(models.Model): """ Photo uploaded by user. """ user = models.ForeignKey(User, related_name='photos') image = models.ImageField(_("image"), upload_to=get_upload_path) title = models.CharField(_("title"), max_length=200) description = models.TextField(_("description"), blank=True, null=True) uploaded_at = models.DateTimeField(_("uploaded at"), auto_now_add=True) rating = RatingField(range=5) def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('photos_show_photo', (), {'photo_id': self.id}) get_absolute_url.short_description = 'url' class Meta: get_latest_by = 'uploaded_at' ordering = ['-uploaded_at'] verbose_name = _('Photo') verbose_name_plural = _('Photos')
class StoreReview(models.Model): product = models.ForeignKey(Product) store = models.ForeignKey(Store) rating = RatingField(range=5) objects = models.Manager() approved = ActiveStoreReviewManager()
class Node(NID): """ Super class """ altnames = TagField(_('alternate names'), help_text=_('alternate names if any'), blank=True, null=True) plural = models.CharField( _('plural name'), help_text=_('plural form of the node name if any'), max_length=255, blank=True, null=True) rating = RatingField(range=5, can_change_vote=True, help_text=_('your rating'), blank=True, null=True) def __unicode__(self): return self.title class Meta: abstract = False
class Recipe(ImageModel): SHARE_SHARED = 0 PRIVATE_SHARED = 1 SHARED_CHOCIES = ( (SHARE_SHARED, _('Share')), (PRIVATE_SHARED, _('Private')), ) title = models.CharField(_("Recipe Title"), max_length=250) slug = AutoSlugField(_('slug'), populate_from='title', unique=True) author = models.ForeignKey(User, verbose_name=_('user')) photo = models.ImageField(_('photo'), blank=True, upload_to="upload/recipe_photos") course = models.ForeignKey(Course, verbose_name=_('course')) cuisine = models.ForeignKey(Cuisine, verbose_name=_('cuisine')) info = models.TextField(_('info'), help_text="enter information about the recipe") cook_time = models.IntegerField(_('cook time'), help_text="enter time in miuntes") servings = models.IntegerField(_('servings'), help_text="enter total number of servings") directions = models.TextField(_('directions')) shared = models.IntegerField( _('shared'), choices=SHARED_CHOCIES, default=SHARE_SHARED, help_text="share the recipe with the community or mark it private") tags = TaggableManager(_('tags'), help_text="separate with commas", blank=True) rating = RatingField(range=5) related = models.OneToOneField('Recipe', verbose_name=_('related'), related_name='RecipeRelated', blank=True, null=True, help_text="related a recipe") pub_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class IKOptions: '''image kit options''' spec_module = 'recipe.ikspec' cache_dir = 'upload/recipe_photos/cache' image_field = 'photo' class Meta: ordering = ['pub_date', 'title'] def __unicode__(self): return self.title def get_absolute_url(self): return "/recipe/%s/" % self.slug def get_reported(self): if ReportedRecipe.objects.filter(recipe=self): return True
class Review(models.Model): user = models.ForeignKey(User) video_game = models.ForeignKey(VideoGame) rating = RatingField(range=5, can_change_vote=True) comments = models.TextField(null=True, blank=True) def __unicode__(self): return '%s - %s' % (self.user, self.video_game)
class RatingTestModel(models.Model): rating = AnonymousRatingField(range=2, can_change_vote=True) rating2 = RatingField(range=2, can_change_vote=False) class Meta: db_table = "djangoratings_ratingtestmodel" def __unicode__(self): return unicode(self.pk)
class Camp(Resource): description = models.TextField() url = models.URLField(max_length=500) address = models.CharField(max_length=500) longitude = models.FloatField(null=True) latitude = models.FloatField(null=True) rating = RatingField(range=5) def __unicode__(self): return self.name
class Mixture(models.Model): """ Represents a hand-made object or service. """ __metaclass__ = TransMeta author = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField( _(u"Name"), max_length=100, help_text=_(u"A mixture short name that describes what it is."), ) slug = models.SlugField(_("Slug name"), blank=True, null=True) short_description = models.CharField( _(u"Short description"), max_length=255, help_text=_(u"Short description about the product."), ) long_description = models.TextField( _(u"Long description"), help_text=_(u"Long description about the product."), ) is_published = models.BooleanField( _(u"Is Published"), default=False, help_text=_(u"Publish the mixture on site."), ) rating = RatingField( range=settings.MIXTURE_MAX_RATE, can_change_vote=True, allow_delete=True, ) category = models.ForeignKey( 'category.Category', null=True, related_name='mixtures', help_text=_(u"The mixture clasification in category."), ) price = models.DecimalField( _('Price'), max_digits=10, decimal_places=2, default=Decimal('0.00'), help_text=_('The mixture price, in USD$.'), ) objects = models.Manager() published = MixtureManager() class Meta: translate = ('name', 'short_description', 'long_description', 'slug') def __unicode__(self): return unicode(self.name)
class Recipe(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=30) body = models.TextField() install_path = models.CharField( "Build Label", max_length=150, blank=True, null=True, help_text= "You can install this package in your system by using this label.") url = models.URLField(max_length=250, blank=True, null=True) date_posted = models.DateField(editable=False, blank=True, null=True) date_updated = models.DateTimeField(editable=False, blank=True, null=True) published = models.BooleanField(default=False) rating = RatingField(range=5) tags = TagField() def set_tags(self, tags): Tag.objects.update_tags(self, tags) def get_tags(self): return Tag.objects.get_for_object(self) def stars(self): return range(self.rating_score) class Meta: ordering = ('-date_updated', ) class Admin: fields = ( ('Metadata', { 'fields': ( 'title', 'author', 'tags', ) }), ('None', { 'fields': ('body') }), ) def save(self): if not self.id: self.date_updated = datetime.datetime.now() if self.published: self.date_posted = datetime.datetime.now() super(Recipe, self).save() def __unicode__(self): return self.title
class Photo(models.Model): author = models.ForeignKey(User) image = models.ImageField(upload_to="upload/photos/%Y/%m/%d", max_length=1000) blurb = models.CharField(max_length=100) rating = RatingField(range=5, can_change_vote=True, allow_delete=True) createdate = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "%s stars (%d): %s" % (str( self.rating.score), self.rating.votes, self.blurb)
class Product (models.Model): product_name = models.CharField(max_length = 50) slug = AutoSlugField(unique=True, populate_from='product_name', editable=True) # product_image = StdImageField(upload_to = 'images/products/main', size=(300, 400, True)) # product_thumbnail = StdImageField(upload_to = 'images/products/thumbnails', size=(100, 100, True),) product_image = StdImageField(upload_to='images/products/main', blank=True, size=(350, 400), thumbnail_size=(100, 100, True)) # all previous features in one declaration rating = RatingField(range=5) Category = models.ManyToManyField(Category) brand = models.CharField(max_length = 25) manufacturer = models.CharField(max_length = 25) Store = models.ForeignKey(Store, null=True) price = models.DecimalField(max_digits = 10, decimal_places = 2, null=True, blank=True) quantity = models.IntegerField(max_length=4,default=1) submitted_at = models.DateTimeField(auto_now_add=True) description = models.TextField() product_type = models.CharField(max_length = 25) product_condition = models.CharField(max_length = 25) product_pricing = models.CharField(max_length = 25) is_active = models.BooleanField(default=False) is_bestseller = models.BooleanField(default=False) is_featured = models.BooleanField(default=False) user = models.ForeignKey(User) objects = models.Manager() active = ActiveProductManager() featured = FeaturedProductManager() bestseller = BestsellerProductManager() def __unicode__ (self): return self.product_name class Meta: db_table ='product' ordering = ['-submitted_at'] verbose_name_plural = 'Products' @models.permalink def get_absolute_url(self): return ('pdcts_product', (), { 'product_slug': self.slug }) def cross_sells_user(self): """ gets other Product instances s who also ordered the current instance. Uses all past orders of each registered customer and not just the order in which the current instance was purchased """ from Nuaza.pdcts.models import ProductReview from django.contrib.auth.models import User users = User.objects.filter(productreview__product=self) items = ProductReview.objects.filter(user__in=users).exclude(product=self) products = Product.active.filter(productreview__in=items).distinct() return products
class Suggestion(models.Model): text = models.CharField(max_length=255) suggested_by = models.ForeignKey(User, related_name="suggested_by") suggested_date = models.DateTimeField(auto_now_add=True) last_modified_date = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) rating = RatingField(range=1, allow_delete=True, can_change_vote=True) resources = models.ManyToManyField(Resource, related_name="resources_added", null=True, blank=True) def __unicode__(self): return '%s' % self.text
class Job(models.Model): Class_Catagory = [('PR', 'Primary (1-5)'), ('JU', 'Junior (6-8)'), ('SSC', 'Scondary (9-10)'), ('HSC', 'Higher Secondary (11-12)')] Subject_Choices = [('M', 'Math'), ('E', 'English'), ('P', 'Physics'), ('C', 'Chemistry'), ('B', 'Biology'), ('BN', 'Bangla'), ('I', 'ICT'), ('CM', 'Computer')] Medium_Choices = [('BM', 'Bangla Medium'), ('EM', 'English Medium'), ('EV', 'English Version(National Curriculam)')] TUTION_CHOICES = (('PR', 'Private'), ('BC', 'Batch'), ('PB', 'Both Private and Batch')) Tutor = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Profile_Pic = models.ImageField(default='/images/propic avater.jpg', upload_to='profile_pic/') Gender = models.CharField(default='', max_length=10) Phone = models.CharField(default='', max_length=15) DOB = models.DateField(default=date(1111, 11, 11)) Address = models.TextField(default='', max_length=150) Religion = models.CharField(default='', max_length=10) Class = MultiSelectField(choices=Class_Catagory, max_choices=3, max_length=15) Subject = MultiSelectField(choices=Subject_Choices, max_length=100) Medium = MultiSelectField(default='', choices=Medium_Choices, max_length=15) Location = models.TextField(max_length=100) Days = models.IntegerField() Tution_Type = models.CharField(choices=TUTION_CHOICES, default='', max_length=15) Salary = models.TextField() Institution = models.CharField(default='', max_length=100) Degree = models.CharField(default='', max_length=100) MySubject = models.CharField(default='', max_length=100) Registration = models.CharField(default='', max_length=30) Vote = models.IntegerField(default=0) rating = RatingField(range=5, can_change_vote=False, allow_anonymous=True, use_cookies=True)
class Alias(Trackable, Activable): slug = models.SlugField(unique=True) content = models.CharField(max_length=2500, validators=[alias_validator]) description = models.CharField(max_length=2500, blank=True) rating = RatingField(range=ALIAS_RATING_RANGE, can_change_vote=True) created_by = models.ForeignKey(User, editable=False) objects = AliasManager() tags = TaggableManager() def get_absolute_url(self): return reverse('aliases:show', args=[self.slug]) def __unicode__(self): return self.content def save(self, *args, **kwargs): self.slug = slugify(self.content) super(Alias, self).save(*args, **kwargs)
class Serie(models.Model): name = models.CharField(max_length=255) slug_name = models.SlugField(unique=True, help_text=_('nombre en la URL')) network = models.ForeignKey("Network", related_name="series") genres = models.ManyToManyField("Genre", related_name="series") runtime = models.IntegerField( name=_('duracion de los episodios'), blank=True, null=True, help_text=_( 'duracion del episodio en minutos' ) ) actors = models.ManyToManyField( "Actor", through='Role', help_text=_('actores que trabajaron en la serie')) description = models.TextField() finished = models.BooleanField( default=False, help_text=_('la serie ha finalizado?') ) rating = RatingField( range=5, can_change_vote=True, help_text=_('puntuacion de estrellas') ) poster = models.OneToOneField( 'ImageSerie', related_name='poster_of', null=True, blank=True ) def __unicode__(self): return self.name def save(self, force_insert=False, force_update=False, using=None): ''' When is saved, the title is converted to slug - aka URL''' self.slug_name = slugify(self.name) super(Serie, self).save(force_insert, force_update, using) @models.permalink def get_absolute_url(self): return ('serie.views.get_serie', (), {'serie_slug': self.slug_name, })
class Store (models.Model): store_name = models.CharField(max_length = 25) slug = AutoSlugField(unique=True) description = models.TextField() contacts = models.TextField() rating = RatingField(range=5) objects = models.Manager() active = ActiveStoreManager() def __unicode__ (self): return self.store_name class Meta: db_table ='store' ordering = ['-store_name'] verbose_name_plural = 'stores' @models.permalink def get_absolute_url(self): return ('pdcts_store', (), { 'store_slug': self.slug })
class Review(CommonInfo): product = models.ForeignKey(to='Product') reviewer = models.ForeignKey(to=User) editor = models.ForeignKey(to=User, null=True, blank=True, related_name='review_editor_user') kicker = models.CharField(max_length = 128, blank = True) subtitle = models.CharField(max_length = 512, blank = True) user_rating = RatingField(range=10, allow_anonymous = True, use_cookies = True) version_tested = models.CharField(max_length=128, blank = True) os_used = models.ManyToManyField('OperatingSystem', blank = True, null = True) review_done = models.DateField(null = True, blank=True) image = models.ImageField( help_text='Review Screenshot? TODO: Standardize Size', max_length=256, upload_to='review_lab/contrib/img/reviews', null=True, blank=True) community = models.IntegerField(choices=RATING_CHOICES, default = 0) community_text = models.CharField(max_length = 256, blank = True) documentation = models.IntegerField(choices=RATING_CHOICES, default = 0) documentation_text = models.CharField(max_length = 256, blank = True) performance = models.IntegerField(choices=RATING_CHOICES, default = 0) performance_text = models.CharField(max_length = 256, blank = True) usability = models.IntegerField(choices=RATING_CHOICES, default = 0, help_text = "General Difficulty level, learning curve.") usability_text = models.CharField(max_length = 256, blank = True) rating = models.IntegerField(choices=RATING_CHOICES, default = 0) rating_text = models.CharField(max_length = 256, blank = True) programming = models.IntegerField(choices=RATING_CHOICES, default = 0) programming_text = models.CharField(max_length = 256, blank = True) def __unicode__(self): return u'%s (Review of: %s)' % (self.name, self.product) @models.permalink def get_absolute_url(self): return ('review_view', (), {'slug': self.slug}) class Meta: ordering = ['-creation_time'] verbose_name = 'Review' verbose_name_plural = 'Reviews'
class EventoBase(Model, CT): categoria = ForeignKey(CategoriaEvento) title = CharField('titulo', max_length=250) description = TextField('descripción', blank=True, null=True) slug = SlugField(db_index=True) rating = RatingField(range=10, can_change_vote=True) start = DateTimeField('comienzo') end = DateTimeField('fin') precio = CharField('precio', max_length=250) poster = ImageField(upload_to='cartelera/posters', blank=True, null=True) type = CharField(max_length=250) def __unicode__(self): return self.title def render(self): return render_to_string([ 'cartelera/%s_lead.html' % self.categoria.slug, 'cartelera/evento_lead.html' ], {'%s' % self.categoria.slug: self}) def get_absolute_url(self): return reverse('evento', args=[self.categoria.slug, self.slug])
class Agency(models.Model): name = models.CharField(max_length=100) logo = models.ImageField(null=True, blank=True, upload_to="agencies_logos", height_field="logo_height", width_field="logo_width") logo_width = models.PositiveIntegerField(blank=True, null=True) logo_height = models.PositiveIntegerField(blank=True, null=True) website = models.CharField(blank=True, null=True, max_length=100) main_office = models.ForeignKey('Office', null=True, blank=True, related_name="main_office") rating = RatingField( range=5, can_change_vote=True, allow_anonymous=False) # 5 possible rating values, 1-5 def __unicode__(self): return self.name class Meta: verbose_name_plural = "agencies"
class Audio(BaseAlbumItem): """ Audios attached """ album = models.ForeignKey(AudioAlbum, verbose_name = "Альбом", null = True, blank = True) file = models.FileField('Аудіозапис', max_length=256, upload_to=upload_filename) downloadable = models.BooleanField('Дозволити скачування', default = False) rating = RatingField('Рейтинг', range=5) @models.permalink def get_absolute_url(self): return ('show_object_detail', ['audio', self.user.username, self.album.slug, self.id]) def __unicode__(self): if self.title: return self.title else: return self.file.name.split("/")[-1]
class Recipe(models.Model): name = models.CharField(max_length=255, unique=True) ingredients = models.TextField() directions = models.TextField() primary_photo = models.CharField(max_length=255, blank=True) inserted = models.DateField(auto_now_add=True) #TODO change to DateTimeField tags = models.ManyToManyField('Tag', blank=True) servings = models.PositiveIntegerField(blank=True, null=True) preparation_time = models.PositiveIntegerField(blank=True, null=True) inserted_by = models.ForeignKey(User, null=True) slug = models.SlugField(unique=True, blank=True) rating = RatingField(range=5, allow_anonymous=True, can_change_vote=True) class Meta: ordering = ['name'] verbose_name = 'recept' def save(self): #TODO if slug already exists, assign another - increasing numbers self.slug = slugify(self.name) models.Model.save(self) def __unicode__(self): return self.name
class Topic(models.Model): ''' Topic is used to hold the latest event about a topic and a committee Fields: title - the title description - its description created - the time a topic was first connected to a committee modified - last time the status or the message was updated editor - the user that entered the data status - the current status log - a text log that keeps text messages for status changes committees - defined using a many to many from `Committee` ''' creator = models.ForeignKey(User) editors = models.ManyToManyField(User, related_name='editing_topics', null=True, blank=True) title = models.CharField(max_length=256, verbose_name=_('Title')) description = models.TextField(blank=True, verbose_name=_('Description')) status = models.IntegerField(choices=( (TOPIC_PUBLISHED, _('published')), (TOPIC_FLAGGED, _('flagged')), (TOPIC_REJECTED, _('rejected')), (TOPIC_ACCEPTED, _('accepted')), (TOPIC_APPEAL, _('appeal')), (TOPIC_DELETED, _('deleted')), ), default=TOPIC_PUBLISHED) rating = RatingField(range=7, can_change_vote=True, allow_delete=True) links = generic.GenericRelation(Link, content_type_field="content_type", object_id_field="object_pk") events = generic.GenericRelation(Event, content_type_field="which_type", object_id_field="which_pk") # no related name as `topics` is already defined in CommitteeMeeting as text committees = models.ManyToManyField(Committee, verbose_name=_('Committees')) meetings = models.ManyToManyField(CommitteeMeeting, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) log = models.TextField(default="", blank=True) class Meta: verbose_name = _('Topic') verbose_name_plural = _('Topics') @models.permalink def get_absolute_url(self): return ('topic-detail', [str(self.id)]) def __unicode__(self): return "%s" % self.title objects = TopicManager() def set_status(self, status, message=''): self.status = status self.log = '\n'.join(( u'%s: %s' % (self.get_status_display(), datetime.now()), u'\t%s' % message, self.log, )) self.save() def can_edit(self, user): return user.is_superuser or user == self.creator or \ user in self.editors.all()
class RatingTestModel(models.Model): rating = AnonymousRatingField(range=2, can_change_vote=True) rating2 = RatingField(range=2, can_change_vote=False) def __unicode__(self): return unicode(self.pk)
class Shareditem(models.Model): """ Parent model for all shared items on the page. The class is using multiple managers for * inheritance and selecting subclasses (default 'objects'), and * for spatial queries ('geo_objects'). """ ITEMTYPES = ( ("i", "Idea"), ("m", "Meeting Note"), ("n", "Newspaper Article"), ("e", "Photo or Video"), # legacy: was 'External Media' ("d", "Data"), ) # used in template tags, added here for maintenance reasons ITEMTYPES_PLURAL = { "i": "Ideas", "m": "Meeting Notes", "n": "Newspaper Articles", "e": "Photos & Videos", "d": "Data", } desc = MarkupField( "Description", help_text= "Please see the <a href='#'>Text formatting cheat sheet</a> for help.") itemtype = models.CharField( max_length=1, choices=ITEMTYPES, ) station = models.ForeignKey("Station", verbose_name="Related Station", null=True, blank=True) theme = models.ForeignKey("Theme", verbose_name="Related Theme", null=True, blank=True) author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) ip = models.IPAddressField(default="127.0.0.1") created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now_add=True, auto_now=True) rating = RatingField(range=5, can_change_vote=True) objects = InheritanceManager() geometry = models.PointField(geography=True, null=True, blank=True) # default SRS 4326 geo_objects = models.GeoManager() class Meta: ordering = ("-created", "author") get_latest_by = "created" def __unicode__(self): return u"%i" % self.id # child model per itemtype CHILDMODELS = { "i": "idea", "m": "meetingnote", "n": "newsarticle", "e": "media", "d": "data", } @permalink def get_absolute_url(self): return ("%s_detail" % (Shareditem.CHILDMODELS[self.itemtype]), None, { "id": self.id, }) def get_comment_count(self): # workaround for problem with for_model method and inheritance contenttype = ContentType.objects.get_for_model(self) return Comment.objects.filter(content_type=contenttype.id, object_pk=self.id).count() def get_child_contenttype(self): return ContentType.objects.get( app_label="participation", model=Shareditem.CHILDMODELS[self.itemtype])
class MinusRecord(models.Model): """ Model That represents voiced-off record http://bitbucket.org/foomor/minus/wiki/MinusArhcive """ user = models.ForeignKey('auth.User', related_name='uploaded_records') file = models.FileField(u'Файл', storage=audio_storage, blank=True, null=True, upload_to=up_filename, max_length=2048) title = models.CharField('Назва', blank=True, help_text="Назва композиції", max_length=255) is_folk = models.BooleanField('Народна композиція', blank=True, default=False) alternative = models.BooleanField( 'Альтернативний запис', help_text='запис не є українською мінусовкою,\ (інструменталки, пісні народів світу, тощо)', blank=True, default=False, ) author = models.ForeignKey(MinusAuthor, verbose_name=u"Виконавець", related_name='records_by', blank=True, null=True) #foreignkey arrangeuathor = models.CharField('Автор аранжування', blank=True, null=True, max_length=50) annotation = models.TextField('Анотація', help_text=u'Додаткові дані, авторські права', blank=True) categories = models.ManyToManyField( MinusCategory, verbose_name=u"Категорії", help_text=u'Жанри до яких належить даний запис. ', null=True, blank=True, related_name='records_in_category') thematics = models.CharField( 'Тематика', max_length=30, blank=True, null=True, help_text=u"Тематика даної композиції, наприклад:\ повстанська, стрілецька, поховальна") tempo = models.CharField('Темп композиції', max_length=10, choices=TEMPO_CHOICES, default="normal") staff = models.CharField('Виконавчий склад', max_length=10, choices=STAFF_CHOICES, help_text=u"колектив, для якого\ призначена дана мінусовка", default="solo") gender = models.CharField('Стать виконавця', max_length=10, choices=GENDER_CHOICES, default="all") is_childish = models.BooleanField('Дитяча', default=False) is_amateur = models.BooleanField( 'Аматорська', default=False, help_text=u"Дана композиція є аматорським записом") is_ritual = models.BooleanField( 'Обрядова', default=False, help_text=u"Виконується на весіллях, святах і т.п.") lyrics = models.TextField('Текст пісні', blank=True) plusrecord = models.URLField('Посилання на плюсовку', blank=True, null=True, help_text="Посилання на файло-обмінник\ або інше місце, звідки можна скачати оригінал", max_length=2048) pub_date = models.DateTimeField(auto_now_add=True) length = models.TimeField(default = datetime.time(0, 0, 0),\ editable = False) bitrate = models.IntegerField(default=0, editable=False) filesize = models.IntegerField(default=0, editable=False) embed_video = models.TextField( "Відео виконання", help_text=u'За бажанням можете вставити відео з\ оригінальним виконанням композиції. Підтримувані\ сервіси: youtube', blank=True, null=True) type = models.ForeignKey(FileType, related_name='matched_records') rating = RatingField('Рейтинг', range=5) def get_absolute_url(self): return ('minus_detail', [self.author, self.id]) get_absolute_url = permalink(get_absolute_url) # :D class Meta: verbose_name = u'Мінусовка' verbose_name_plural = u'Мінусовки на сайті' ordering = ['-pub_date'] def __unicode__(self): try: return u"%s - %s" % (self.author, self.title) except MinusAuthor.DoesNotExist: #STRANGEBUUG!!! self.author, created = MinusAuthor.objects.get_or_create( name="Невідомий Виконавець") self.save() return u"%s - %s" % (self.author, self.title)
from django.test import TestCase from django.contrib.auth.models import User from django.contrib.sites.models import Site from djangoratings.fields import RatingField rating_field = RatingField(weight=0, range=5, allow_multi_vote=True) rating_field.contribute_to_class(Site, 'rating') class MultiVoteTest(TestCase): def test_multi_vote(self): """ Test to rate the same object multiple times by the same user """ site = Site.objects.get_current() user, created = User.objects.get_or_create(username='******') site.rating.add(1, user, '127.0.0.1') site.rating.add(2, user, '127.0.0.1') site.rating.add(3, user, '127.0.0.1') self.failUnlessEqual(site.rating.get_rating(), 2) self.failUnlessEqual(site.rating.votes, 3) self.failUnlessEqual(site.rating.score, 6)
class Firm( MPTTModel ): #модель БД для фирм и организаций, наследуется от класса. поддерживающего дерево #далее просто указываеются все необходимые поля #поле "имя" - не проверяется, но должно быть уникально в пределах категории. name = models.CharField(max_length=50, verbose_name='Название') #поле "псевдоним" - не проверяется, но должно быть уникально в пределах категории. alias = models.CharField(max_length=50, unique=True, verbose_name='Псевдоним') #указание поля, благодаря которому древовидная стукрута вообще работает parent = TreeForeignKey('self', null=True, blank=True, related_name='children') #Логическая переменная, определяющая, по сути, в каком шаблоне отображать модель container = models.BooleanField(verbose_name='Контейнер?') #короткое описание, показывается на карте и в отображении списком short = tinymce_models.HTMLField(verbose_name='Короткое описание', null=True, blank=True) #Полный текст описания фирмы description = tinymce_models.HTMLField(verbose_name='Полный текст', null=True, blank=True) #изображения, привязанные к фирме #image1 = models.ImageField(upload_to='uploads', verbose_name='Изображение 1', null=True, blank=True) image1 = models.ImageField(upload_to='uploads', verbose_name='Изображение 1', null=True, blank=True) image2 = models.ImageField(upload_to='uploads', verbose_name='Изображение 2', null=True, blank=True) image3 = models.ImageField(upload_to='uploads', verbose_name='Изображение 3', null=True, blank=True) image4 = models.ImageField(upload_to='uploads', verbose_name='Изображение 4', null=True, blank=True) #ключевые слова meta_key = models.CharField(max_length=100, verbose_name='Ключевые слова', null=True, blank=True) #строка адреса фирмы location = models.CharField(max_length=100, verbose_name='Адрес', null=True, blank=True) lat = models.CharField(max_length=255, verbose_name='Широта', null=True, blank=True) lng = models.CharField(max_length=255, verbose_name='Долгота', null=True, blank=True) #стиль отображения на карте. Проще сделать отдельной таблицей все значения. map_style = models.ForeignKey(MapStyle, verbose_name='Стиль на карте', null=True, blank=True) #Логическая переменная, определяющая, является ли данный объект магазином isstore = models.BooleanField(verbose_name='Магазин?') #поле "ecwid" - необходимое поле в случае, если ресурс - магазин. ecwid = models.CharField(max_length=50, verbose_name='ID магазина ECWID', null=True, blank=True) #дата создания ресурса pub_date = models.DateTimeField('Дата публикации') #переменная для количества голосов totalvotes = models.BigIntegerField( verbose_name='Количество проголосовавших', null=True) #переменная для подсчёта рейтинга raiting = models.FloatField(verbose_name='Рейтинг', null=True) rating = RatingField(range=5, allow_anonymous=True, use_cookies=True) class MPTTMeta: #метадата для деревьев order_insertion_by = ['name'] def __unicode__( self ): #дополнительное поле, определяет информацию. выводимю на экран return self.name