コード例 #1
0
class Product(models.Model):
    name = models.CharField(verbose_name='name',
                            max_length=100,
                            blank=False,
                            null=False)

    amount = models.IntegerField(verbose_name='amount', blank=True, null=True)

    price = models.IntegerField(verbose_name='price', blank=False, null=False)

    intro = models.CharField(verbose_name='intro',
                             max_length=200,
                             blank=True,
                             null=True)

    image = StdImageField(
        verbose_name='image',
        upload_to="product",
        validators=[MinSizeValidator(300, 300),
                    MaxSizeValidator(5760, 3840)],
        blank=True,
        variations={
            'medium': (500, 500, True),
            'small': (300, 300, True),
        },
    )

    tx_hash = models.CharField(verbose_name='name',
                               max_length=2000,
                               blank=False,
                               null=False)

    def __str__(self):
        return self.name
コード例 #2
0
ファイル: models.py プロジェクト: entropia/gulasch-r0mstore
class Rom(models.Model):
    name = models.CharField("name", max_length=128, unique=True)
    description = models.TextField("Beschreibung", max_length=1024)
    cover = StdImageField("cover-Bild",
                          upload_to=upload_cover_to,
                          validators=[MinSizeValidator(300, 300)],
                          variations={
                              'large': {
                                  'width': 600,
                                  'height': 600,
                                  'crop': True
                              },
                              'small': {
                                  'width': 300,
                                  'height': 300,
                                  'crop': True
                              }
                          })
    low_binary = models.FileField("low binary", upload_to=upload_binary_to)
    high_binary = models.FileField("high binary", upload_to=upload_binary_to)
    approved = models.BooleanField("approved", default=False)
    tags = TaggableManager(blank=True)
    user = models.ForeignKey(User,
                             blank=True,
                             null=True,
                             on_delete=models.PROTECT)
    download_count = models.IntegerField(default=0)
    creation_time = models.DateTimeField("creation time", auto_now_add=True)
    edit_time = models.DateTimeField("edit time", auto_now=True)

    def get_absolute_url(self):
        return reverse('romdetails', kwargs={'id': self.pk})

    def tag_list(self):
        return [t.name for t in self.tags.all()]

    def to_json(self):
        json = {
            'id': self.pk,
            'name': self.name,
            'user': self.user.username,
            'description': self.description,
            'tags': self.tag_list(),
            'low_binary': self.low_binary.url,
            'high_binary': self.high_binary.url,
            'download_count': self.download_count,
            'creation_time': self.creation_time,
            'edit_time': self.edit_time
        }

        return json

    def __str__(self):
        return self.name
コード例 #3
0
class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    categories = models.ManyToManyField(Category)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    image = StdImageField(
        upload_to=upload_to_pattern,
        blank=True,
        null=True,
        variations={
            "home": {
                "width": 530,
                "height": 220,
                "crop": True
            },
            "mobilethumb": {
                "width": 580,
                "height": 150,
                "crop": True
            },
            "thumbnail": {
                "width": 250,
                "height": 150,
                "crop": True
            },
            "full": {
                "width": 825,
                "height": 450,
                "crop": True
            },
        },
        validators=[MinSizeValidator(730, 410)],
    )

    description = MartorField()
    excerpt = models.TextField(blank=True, null=True)
    published_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(default=timezone.now)
    active = models.BooleanField(default=True)
    members_only = models.BooleanField(default=False)
    sent_on_social = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("blog-item", kwargs={"slug": self.slug})

    class Meta:
        ordering = ("-published_date", )
コード例 #4
0
class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    categories = models.ManyToManyField(Category)
    author = models.ForeignKey(User)
    image = StdImageField(
        upload_to=UploadToAutoSlugClassNameDir(populate_from='title'),
        blank=True,
        null=True,
        variations={
            'home': {
                "width": 530,
                "height": 220,
                "crop": True
            },
            'mobilethumb': {
                "width": 580,
                "height": 150,
                "crop": True
            },
            'thumbnail': {
                "width": 250,
                "height": 150,
                "crop": True
            },
            'full': {
                "width": 825,
                "height": 450,
                "crop": True
            }
        },
        validators=[MinSizeValidator(730, 410)])

    description = MartorField()
    excerpt = models.TextField(blank=True, null=True)
    published_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(default=timezone.now)
    active = models.BooleanField(default=True)
    members_only = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog-item', kwargs={'slug': self.slug})

    class Meta:
        ordering = ('-published_date', )
コード例 #5
0
class Idea(models.Model):
    user = models.ForeignKey(Account,
                             related_name='ideas',
                             on_delete=models.CASCADE)
    title = models.CharField(verbose_name=_('Title'), max_length=255)
    topic = models.IntegerField(
        verbose_name=_('Topic'),
        choices=IDEA_TOPIC_CHOICES,
    )
    description = models.TextField()
    image = StdImageField(verbose_name=_('Image'),
                          default='default/img/idea.png',
                          upload_to=UploadToPathAndRename('upload/img/idea'),
                          validators=[
                              FileExtensionValidator(['png', 'jpg', 'jpeg']),
                              MinSizeValidator(200, 200),
                              MaxSizeValidator(1200, 1200)
                          ],
                          variations={
                              'thumbnail': (40, 40, True),
                              'medium': (200, 200, True),
                              'large': (525, 525, True),
                          },
                          blank=True,
                          null=True)
    file = models.FileField(
        verbose_name=_('Resume'),
        upload_to=UploadToPathAndRename('upload/file/resume'),
        validators=[
            FileExtensionValidator(['pdf', 'doc', 'docx']),
        ],
        blank=True,
        null=True)
    update_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = _('idea')
        verbose_name_plural = _('ideas')
        ordering = ['-created_at']

    def __str__(self):
        return ('%s add by %s' %
                (self.title, self.user.get_full_name())).strip()

    def get_topic_str(self):
        return IDEA_TOPIC_CHOICES[self.topic - 1][1]
コード例 #6
0
class BannerImage(models.Model):
    url = models.URLField()
    title = models.CharField(max_length=255)
    displayed = models.BooleanField(default=True)
    image = StdImageField(
        upload_to=UploadToAutoSlugClassNameDir(populate_from='title'),
        variations={
            'small': {
                "width": 400,
                "height": 300,
                "crop": True},
            'small2x': {
                "width": 800,
                "height": 600,
                "crop": True},
            'medium': {
                "width": 800,
                "height": 300,
                "crop": True},
            'medium2x': {
                "width": 1600,
                "height": 600,
                "crop": True},
            'large': {
                "width": 1200,
                "height": 300,
                "crop": True},
            'large2x': {
                "width": 2400,
                "height": 600,
                "crop": True}},
        validators=[
            MinSizeValidator(2400, 600)])

    caption = models.TextField()
    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title
コード例 #7
0
class BannerImage(models.Model):
    url = models.URLField()
    title = models.CharField(max_length=255)
    displayed = models.BooleanField(default=True)
    image = StdImageField(
        upload_to=upload_to_pattern,
        variations={
            "small": {"width": 400, "height": 300, "crop": True},
            "small2x": {"width": 800, "height": 600, "crop": True},
            "medium": {"width": 800, "height": 300, "crop": True},
            "medium2x": {"width": 1600, "height": 600, "crop": True},
            "large": {"width": 1200, "height": 300, "crop": True},
            "large2x": {"width": 2400, "height": 600, "crop": True},
        },
        validators=[MinSizeValidator(2400, 600)],
    )

    caption = models.TextField()
    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title
コード例 #8
0
class MyUser(AbstractUser):
    """ Model to store all auth users """
    # add custom fiels for default User profile HERE
    avatar = MyImageField(
        upload_to=avatar_directory_path,  # path/to/imgs
        variations={'thumbnail': (150, 150, True)},  # resize to min size
        validators=[
            validate_avatar_size,  # size
            MinSizeValidator(150, 150),  # min dimension
            MaxSizeValidator(500, 500)
        ],  # max dimension
        delete_orphans=True,  # delete orphaned files
        blank=True,
    )
    date_of_birth = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.username

    class Meta:
        ordering = ['username']
        verbose_name = "My User"
        verbose_name_plural = "My Users"
コード例 #9
0
class MinSizeModel(models.Model):
    image = StdImageField(upload_to=upload_to,
                          validators=[MinSizeValidator(200, 200)])
コード例 #10
0
class Account(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(
        verbose_name=_('Username'),
        max_length=100,
        unique=True,
        validators=[USERNAME_VALIDATOR],
        help_text=
        _('Required. 100 characters or fewer. Letters, digits and @/ ./+ /- /_ only. e.g. Adam_99'
          ))
    email = models.EmailField(verbose_name=_('Email'),
                              max_length=200,
                              unique=True,
                              help_text=_('Email: e.g. [email protected]'))
    first_name = models.CharField(verbose_name=_('First Name'), max_length=100)
    last_name = models.CharField(verbose_name=_('Last Name'), max_length=100)

    profile_pic = StdImageField(
        verbose_name=_('Profile Image'),
        default='default/img/profile.png',
        upload_to=UploadToPathAndRename('upload/img/profile'),
        validators=[
            FileExtensionValidator(['png', 'jpg', 'jpeg']),
            MinSizeValidator(200, 200),
            MaxSizeValidator(1200, 1200)
        ],
        variations={
            'thumbnail': (40, 40, True),
            'medium': (200, 200, True),
            'large': (525, 525, True),
        })

    country = CountryField(verbose_name=_('Country'),
                           blank_label=_('__Select Country__'))

    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_supervisor = models.BooleanField(default=False)
    is_team = models.BooleanField(default=False)
    is_user = models.BooleanField(default=False)

    global_token = models.CharField(max_length=255, default=uuid4)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'first_name', 'last_name']

    objects = AccountManager()

    class Meta:
        verbose_name = _('account')
        verbose_name_plural = _('accounts')

    def __str__(self):
        return ('%s' % self.username).strip()

    def get_full_name(self):
        return ('%s %s' % (self.first_name, self.last_name)).strip()

    def get_short_name(self):
        return ('%s' % self.first_name).strip()

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
コード例 #11
0
class MinSizeModel(models.Model):
    image = StdImageField(upload_to=UploadTo(name='image', path='img'),
                          validators=[MinSizeValidator(200, 200)])
コード例 #12
0
class Announcement(models.Model):
    objects = AnnouncementQuerySet.as_manager()

    title = models.CharField(
        verbose_name="Titre de l'annonce",
        max_length=200,
        help_text=
        "Ce texte sera utilisé comme titre et texte du lien de l'annonce",
        blank=False,
    )

    link = models.URLField(verbose_name="Lien", blank=False)

    content = DescriptionField(verbose_name="Contenu", blank=False)

    image = StdImageField(
        verbose_name="Bannière",
        validators=[MinSizeValidator(255, 160)],
        variations={
            "desktop": {
                "width": 255,
                "height": 130,
                "crop": True
            },
            "mobile": {
                "width": 160,
                "height": 160,
                "crop": True
            },
        },
        upload_to=dynamic_filenames.FilePattern(
            filename_pattern=
            "activity/announcements/{uuid:.2base32}/{uuid:s}{ext}"),
        null=True,
        blank=True,
    )

    start_date = models.DateTimeField(verbose_name="Date de début",
                                      default=timezone.now)
    end_date = models.DateTimeField(verbose_name="Date de fin",
                                    null=True,
                                    blank=True)

    segment = models.ForeignKey(
        to="mailing.Segment",
        on_delete=models.CASCADE,
        related_name="notifications",
        related_query_name="notification",
        null=True,
        blank=True,
        help_text=
        ("Segment des personnes auquel ce message sera montré (laisser vide pour montrer à tout le monde)"
         ),
    )

    priority = models.IntegerField(
        verbose_name="Priorité",
        default=0,
        help_text=
        "Permet de modifier l'ordre d'affichage des annonces. Les valeurs plus élevées sont affichées avant."
        " Deux annonces de même priorité sont affichées dans l'ordre anti-chronologique (par date de début)",
    )

    def __str__(self):
        return f"« {self.title} »"

    class Meta:
        verbose_name = "Annonce"
        indexes = (models.Index(
            fields=("-start_date", "end_date"),
            name="announcement_date_index",
        ), )
        ordering = ("-start_date", "end_date")
コード例 #13
0
class Course(TimeStampedModel, ChangedByMixin):
    """ Publisher Course model. It contains fields related to the course intake form."""

    title = models.CharField(max_length=255, default=None, null=True, blank=True, verbose_name=_('Course title'))
    number = models.CharField(max_length=50, null=True, blank=True, verbose_name=_('Course number'))
    short_description = models.CharField(
        max_length=255, default=None, null=True, blank=True, verbose_name=_('Brief Description')
    )
    full_description = models.TextField(default=None, null=True, blank=True, verbose_name=_('Full Description'))
    organizations = models.ManyToManyField(
        Organization, blank=True, related_name='publisher_courses', verbose_name=_('Partner Name')
    )
    level_type = models.ForeignKey(
        LevelType, default=None, null=True, blank=True, related_name='publisher_courses', verbose_name=_('Level Type')
    )
    expected_learnings = models.TextField(default=None, null=True, blank=True, verbose_name=_("Expected Learnings"))
    syllabus = models.TextField(default=None, null=True, blank=True)
    prerequisites = models.TextField(default=None, null=True, blank=True, verbose_name=_('Prerequisites'))
    learner_testimonial = models.CharField(max_length=50, null=True, blank=True)
    verification_deadline = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name=_("Verification deadline"),
        help_text=_('Last date/time on which verification for this product can be submitted.')
    )

    primary_subject = models.ForeignKey(
        Subject, default=None, null=True, blank=True, related_name='publisher_courses_primary'
    )
    secondary_subject = models.ForeignKey(
        Subject, default=None, null=True, blank=True, related_name='publisher_courses_secondary'
    )
    tertiary_subject = models.ForeignKey(
        Subject, default=None, null=True, blank=True, related_name='publisher_courses_tertiary'
    )

    image = StdImageField(
        upload_to=UploadToFieldNamePath(
            populate_from='number',
            path='media/publisher/courses/images'
        ),
        blank=True,
        null=True,
        variations={
            'thumbnail': (100, 100, True),
        },
        validators=[MaxSizeValidator(2120, 1192), MinSizeValidator(2120, 1192), ]
    )

    is_seo_review = models.BooleanField(default=False)
    keywords = TaggableManager(blank=True, verbose_name='keywords')

    history = HistoricalRecords()

    def __str__(self):
        return self.title

    @property
    def post_back_url(self):
        return reverse('publisher:publisher_courses_edit', kwargs={'pk': self.id})

    class Meta(TimeStampedModel.Meta):
        permissions = (
            ('view_course', 'Can view course'),
        )

    def get_course_users_emails(self):
        """ Returns the list of users emails with enable email notifications
        against a course. By default if attribute value does not exists
        then user will be eligible for emails.
        """
        users_list_roles = [obj.user for obj in self.course_user_roles.all()]

        user_emails = [user.email for user in users_list_roles if is_email_notification_enabled(user)]

        return user_emails

    @property
    def keywords_data(self):
        keywords = self.keywords.all()
        if keywords:
            return ', '.join(k.name for k in keywords)

        return None

    @property
    def project_coordinator(self):
        try:
            return self.course_user_roles.get(role=PublisherUserRole.ProjectCoordinator).user
        except CourseUserRole.DoesNotExist:
            return None

    def assign_organization_role(self, organization):
        """
        Create course-user-roles except CourseTeam for the given organization against a course.
        """
        for user_role in organization.organization_user_roles.exclude(role=PublisherUserRole.CourseTeam):
            CourseUserRole.add_course_roles(self, user_role.role, user_role.user)

    @property
    def course_runs(self):
        return self.publisher_course_runs.order_by('-created')

    @property
    def course_team_admin(self):
        try:
            return self.course_user_roles.get(role=PublisherUserRole.CourseTeam).user
        except CourseUserRole.DoesNotExist:
            return None

    @property
    def partner(self):
        organization = self.organizations.all().first()
        return organization.partner if organization else None

    @property
    def marketing_reviewer(self):
        try:
            return self.course_user_roles.get(role=PublisherUserRole.MarketingReviewer).user
        except CourseUserRole.DoesNotExist:
            return None

    @property
    def organization_extension(self):
        organization = self.organizations.all().first()
        if organization:
            return organization.organization_extension

        return None

    @property
    def publisher(self):
        try:
            return self.course_user_roles.get(role=PublisherUserRole.Publisher).user
        except CourseUserRole.DoesNotExist:
            return None
コード例 #14
0
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_DIRS = []

AUTH_USER_MODEL = "members.User"
MEDIA_URL = "/media/"

MAX_ZIPFILE = 48 * 1024 * 1024
MIN_IMAGE_SIZE = 2 * 1024
MAX_IMAGE_SIZE = 8 * 1024 * 1024
MAX_IMAGE_WIDTH = 1280

from stdimage.validators import MinSizeValidator, MaxSizeValidator

IMG_VALIDATORS = [MinSizeValidator(100, 100), MaxSizeValidator(8000, 8000)]

# Note: the labels are effectively 'hardcoded' in the templates
# and code; the sizes are free to edit.
#
IMG_VARIATIONS = {
    "thumbnail": (100, 100, True),
    "medium": (300, 200),
    "large": (600, 400),
}

UFO_DEADLINE_DAYS = 14
UFO_DISPOSE_DAYS = 7

CACHES = {
    "default": {
コード例 #15
0
class Universidad(models.Model):
    PUBLICA = 0
    PRIVADA = 1

    def __init__(self, *args, **kwargs):
        self.get_siglas_no_centro = self._get_siglas_no_centro
        super(Universidad, self).__init__(*args, **kwargs)

    TIPO_UNIVERSIDAD_CHOICES = ((PUBLICA, 'Pública'), (PRIVADA, 'Privada'))

    siglas = models.CharField(
        max_length=20,
        unique=True,
        null=False,
        blank=False,
        validators=[
            RegexValidator(
                regex=r'[A-Za-z\-]+',
                message=ugettext_lazy(
                    "Las siglas de la universidad solo pueden contener letras y guiones (-)"
                ))
        ],
        help_text=ugettext_lazy("Siglas de la universidad"))
    nombre = models.CharField(
        max_length=200,
        null=False,
        blank=False,
        help_text=ugettext_lazy("Nombre de la universidad"))
    tipo = models.IntegerField(
        choices=TIPO_UNIVERSIDAD_CHOICES,
        null=False,
        blank=False,
        help_text=ugettext_lazy("Tipo de centro (público/privado)"))
    centro = models.CharField(max_length=200,
                              null=True,
                              blank=True,
                              help_text=ugettext_lazy("Nombre del centro"))
    provincia = models.CharField(max_length=50,
                                 choices=provincias,
                                 blank=False,
                                 null=False,
                                 help_text=ugettext_lazy("Provincia"))
    logo = StdImageField(upload_to=settings.ESCUDOS_PATH,
                         null=True,
                         blank=True,
                         variations={'thumbnail': (100, 100, True)},
                         validators=[MinSizeValidator(100, 100)],
                         help_text=ugettext_lazy("Escudo de la universidad"))

    campus = models.CharField(
        max_length=200,
        null=True,
        blank=True,
        help_text=ugettext_lazy(
            "Nombre del campus"))  # TODO: Hacer obligatorio?
    url = models.URLField(max_length=300,
                          null=True,
                          blank=True,
                          help_text=ugettext_lazy("URL del centro"))

    def _get_siglas_no_centro(self):
        return self.get_siglas_no_centro(self.siglas)

    @staticmethod
    def get_siglas_no_centro(siglas):
        """
        Elimina el sufijo del centro, útil para procesar imágenes
        Returns:

        """
        return re.sub(r'\-.*', '', siglas)

    def get_provincia_unicode(self):
        return dict(provincias).get(self.provincia)

    @property
    def tipo_universidad_verbose(self):
        return self.get_tipo_universidad_verbose(self.tipo)

    @classmethod
    def get_tipo_universidad_verbose(cls, tipo_universidad):
        #self
        return str(
            dict((tipo, nombre) for tipo, nombre in
                 cls.TIPO_UNIVERSIDAD_CHOICES).get(tipo_universidad))

    def __str__(self):
        return self.nombre