How to use the django.db.models.Model function in Django

To help you get started, we’ve selected a few Django examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Kemaweyan / django-content-gallery / content_gallery_testapp / testapp / models.py View on Github external
from django.db import models

from content_gallery.models import ContentGalleryMixin

# the ContentGalleryMixin enables the Content Gallery for the model

class Cat(ContentGalleryMixin, models.Model):

    SEX_CHOICES = {
        ('M', "Male"),
        ('F', "Female")
    }

    name = models.CharField(max_length=50)
    age = models.IntegerField(null=True, blank=True)
    sex = models.CharField(
        max_length=1,
        choices=SEX_CHOICES,
        null=True,
        blank=True
    )
    about = models.TextField(null=True, blank=True)
github RealGeeks / django-modelclone / sampleproject / posts / models.py View on Github external
content = models.TextField()

    def __unicode__(self):
        return u'Comment on {0} by {1}'.format(self.post, self.author)

    __str__ = __unicode__

class Tag(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

    __str__ = __unicode__

class Multimedia(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    title = models.CharField(max_length=256)
    image = models.ImageField(upload_to='images', blank=True)
    document = models.FileField(upload_to='documents', blank=True)

    def __unicode__(self):
        msg = [self.title]
        if self.image:
            msg.append('Image: ' + unicode(self.image))
        if self.document:
            msg.append('Document: ' + unicode(self.document))
        return u' '.join(msg)

    __str__ = __unicode__
github erudit / eruditorg / eruditorg / core / subscription / abstract_models.py View on Github external
# -*- coding: utf-8 -*-

from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _


class AbstractSubscription(models.Model):
    """ An abstract model that can be used to define a Subscription-like model. """
    created = models.DateTimeField(auto_now_add=True, verbose_name=_('Date de création'))
    updated = models.DateTimeField(auto_now=True, verbose_name=_('Date de modification'))

    class Meta:
        abstract = True


class AbstractSubscriptionPeriod(models.Model):
    """ Defines a period in which a subscription is valid. """
    start = models.DateField(verbose_name=_('Date de début'))
    end = models.DateField(verbose_name=_('Date de fin'))

    class Meta:
        abstract = True
github comic / grand-challenge.org / app / comicmodels / migrations / 0001_initial.py View on Github external
),
        migrations.CreateModel(
            name='FileSystemDataset',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.SlugField(max_length=64, blank=True)),
                ('permission_lvl', models.CharField(default=b'ALL', max_length=3, choices=[(b'ALL', b'All'), (b'REG', b'Registered users only'), (b'ADM', b'Administrators only')])),
                ('description', models.TextField()),
                ('folder', models.FilePathField()),
                ('comicsite', models.ForeignKey(help_text=b'To which comicsite does this object belong?', to='comicmodels.ComicSite')),
            ],
            options={
                'abstract': False,
                'permissions': (('view_ComicSiteModel', 'Can view Comic Site Model'),),
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Page',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.SlugField(max_length=64, blank=True)),
                ('permission_lvl', models.CharField(default=b'ALL', max_length=3, choices=[(b'ALL', b'All'), (b'REG', b'Registered users only'), (b'ADM', b'Administrators only')])),
                ('order', models.IntegerField(default=1, help_text=b'Determines order in which page appear in site menu', editable=False)),
                ('display_title', models.CharField(default=b'', help_text=b'On pages and in menu items, use this text. Spaces and special chars allowed here. Optional field. If emtpy, title is used', max_length=255, blank=True)),
                ('hidden', models.BooleanField(default=False, help_text=b'Do not display this page in site menu')),
                ('html', ckeditor.fields.RichTextField()),
                ('comicsite', models.ForeignKey(help_text=b'To which comicsite does this object belong?', to='comicmodels.ComicSite')),
            ],
            options={
                'ordering': ['comicsite', 'order'],
                'abstract': False,
github modoboa / modoboa / modoboa / admin / models / mailbox.py View on Github external
class QuotaManager(models.Manager):
    """Custom manager for Quota."""

    def get_domain_usage(self, domain):
        """Return current usage for domain."""
        qset = self.get_queryset().filter(
            username__endswith="@{}".format(domain.name))
        result = qset.aggregate(usage=models.Sum("bytes")).get("usage", 0)
        if result is None:
            result = 0
        return result


class Quota(models.Model):

    """Keeps track of Mailbox current quota."""

    username = models.EmailField(primary_key=True, max_length=254)
    bytes = models.BigIntegerField(default=0)  # NOQA:A003
    messages = models.IntegerField(default=0)

    objects = QuotaManager()

    class Meta:
        app_label = "admin"


class MailboxManager(Manager):

    """Custom manager for Mailbox."""
github evildmp / Arkestra / news_and_events / models.py View on Github external
def get_admin_title(self):
        return self.title + " (" + self.get_dates() + ")"


class EventType(models.Model):
    event_type = models.CharField(max_length=50)

    class Meta:
        ordering = ['event_type']

    def __unicode__(self):
        return self.event_type


class NewsSource(models.Model):
    external_news_source = models.CharField(max_length=50)

    def __unicode__(self):
        return self.external_news_source


def receiver_function(sender, **kwargs):
    event = kwargs['instance']
    event.get_root().check_date()

post_save.connect(receiver_function, sender = Event)


class NewsAndEventsPlugin(CMSPlugin, ArkestraGenericPluginOptions):
    DISPLAY = (
        ("news & events", u"News and events"),
github EventKit / eventkit-cloud / eventkit_cloud / auth / models.py View on Github external
from django.contrib.auth.models import User, Group
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import JSONField
from django.db import models

from eventkit_cloud.core.models import JobPermission


class OAuth(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
    identification = models.CharField(max_length=200, unique=True, blank=False)
    commonname = models.CharField(max_length=100, blank=False)
    user_info = JSONField(default=dict)

    class Meta:  # pragma: no cover
        managed = True
        db_table = "auth_oauth"

    def __str__(self):
        return "{0}".format(self.commonname)


def delete(self):
    for job_permission in JobPermission.objects.filter(object_id=self.pk):
        job_permission.content_type = ContentType.objects.get_for_model(User)
github phpmyadmin / website / files / models.py View on Github external
for version in settings.LISTED_BRANCHES:
        min_vernum = Release.parse_version(version)
        max_vernum = min_vernum + delta
        stable_releases = Release.objects.filter(
            version_num__gte=min_vernum,
            version_num__lt=max_vernum,
            stable=True,
        )
        if stable_releases.exists():
            result.append(stable_releases[0])

    return result


class Release(models.Model):
    version = models.CharField(max_length=50, unique=True)
    version_num = models.IntegerField(default=0, unique=True)
    release_notes = MarkupField(default_markup_type='markdown')
    stable = models.BooleanField(default=False, db_index=True)
    snapshot = models.BooleanField(default=False, db_index=True)
    date = models.DateTimeField(db_index=True, default=timezone.now)

    purged = False

    class Meta(object):
        ordering = ['-version_num']

    def __unicode__(self):
        return self.version

    def get_absolute_url(self):
github hegusung / WebHashcat / WebHashcat / Utils / models.py View on Github external
from django.db import models

from Hashcat.models import Hashfile

# Create your models here.

# Table used to prevent concurrent access to files
# possible lock_ressource values:
#   - potfile
#   - hashfile
#   - crackedfile
class Lock(models.Model):
    hashfile = models.ForeignKey(Hashfile, on_delete=models.CASCADE)
    lock_ressource = models.CharField(max_length=30)

class Task(models.Model):
    time = models.DateTimeField()
    message = models.TextField()
github coogger / coogger / cooggerapp / models.py View on Github external
class Comment(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE,verbose_name="yorum yapan kiÅŸi")
    content = models.ForeignKey("Blog", on_delete=models.CASCADE,verbose_name="hangi içeriğe yorum yapmış")
    date = models.DateTimeField(default = timezone.now,verbose_name="tarih")
    comment = models.CharField(max_length=310,verbose_name="Soru sor veya teşekkür et, yorum yap")

class Notification(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE,verbose_name="bildirimin gittiÄŸi kiÅŸi")
    even = models.IntegerField(verbose_name="bildirime sebeb olan olay numarası")
    content = models.CharField(max_length=310,verbose_name="bildirim mesajı")
    show = models.BooleanField(default=False,verbose_name="gördü/görmedi")
    address = models.SlugField(verbose_name="bildirimin gerçekleştiği adres")
    time = models.DateTimeField(default = timezone.now,verbose_name="tarih")

class SearchedWords(models.Model):
    word = models.CharField(unique=True,max_length=310,verbose_name="aranan kelime")
    hmany = models.IntegerField(default = 0,verbose_name="kaç defa arandı")