Django

Django

Explore django code snippets and tutorials

Django

Basic gallery model for django

<p>This code appears to be a simplified Django model implementation for a Gallery and Image management system. Let&#39;s go through the code and understand its structure and purpose:</p> <ol> <li> …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import datetime
from django.db import models
from django.utils.translation import ugettext as _


class Timestamped(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class Published(models.Model):
    is_published = models.BooleanField(default=False)

    class Meta:
        abstract = True


class Gallery(Timestamped, Published):
    name = models.CharField(max_length=100)

    class Meta:
        default_related_name = 'galleries'
        verbose_name = _('gallery')
        verbose_name_plural = _('galleries')

    def __str__(self):
        return self.name


def get_upload_path(instance, filename):
    return os.path.join('{}/{}/{}/{}/{}'.format(
        instance.gallery.name, datetime.datetime.now().day,
        datetime.datetime.now().month,
        datetime.datetime.now().year, filename))


class Image(Timestamped, Published):
    gallery = models.ForeignKey(Gallery)
    image = models.ImageField(upload_to=get_upload_path)

    class Meta:
        default_related_name = 'images'
        verbose_name = _('image')
        verbose_name_plural = _('images')

    def __str__(self):
        return self.image.name
Django

Django add permissions programmatically

django add permissions programmatically

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType

User = get_user_model()

def set_permissions(apps=None, models=None, user=None, group=None):
    '''
    It is used to add permisions dynamically to a group.
    Then user is assigned to this group

    PROJECT_GROUP: is a string for example 'website_group'

    user: is a user instance

    apps: is a list of installed apps
    for example apps = ['catalogue', 'products']

    models: is a list of models
    for example models = ['category', 'task']


    '''
    perms = []
    group_name = group if group else settings.PROJECT_GROUP
    group, created = Group.objects.get_or_create(name=group_name)
    if user:
        group.user_set.add(user)
    if apps:
        for app in apps:
            app_models = apps.get_app_config(app).get_models()
            for model in app_models:
                content_type = ContentType.objects.get_for_model(model)
                permissions = Permission.objects.filter(
                    content_type=content_type)
                perms.append(permissions)
    if models:
        for model in self.models:
            content_type = ContentType.objects.get(model=model)
            permissions = Permission.objects.filter(
                content_type=content_type)
            perms.append(permissions)
    if group:
        for p in perms:
            group.permissions.add(*[perm for perm in p])
Django

Django mixin for reusable absolute url method

Django mixin for reusable absolute url method

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.urls import reverse

class AbsoluteUrlMixin:
    '''
    Example:
        class Category(AbsoluteUrlMixin, models.Model):
            name = models.CharField(max_length=100)

            url_name = 'update'

        I use the convention as pattern:

            app_name.model_name.detail

    '''
    def get_absolute_url(self):
        kwargs = {}
        slug = hasattr(self, 'slug')
        url_name = hasattr(self, 'url_name')
        kwargs['pk'] = self.pk
        if not url_name:
            url_name = 'detail'
        if slug:
            kwargs['slug'] = self.slug
        return reverse('{}.{}.{}'.format(self._meta.app_label,
            self.__class__.__name__.lower(), url_name), kwargs=kwargs)