Django

Django

Explore django code snippets and tutorials

Django

Django file validation

<p>The code provided seems to be a part of a Django form that handles file uploads for a model named <code>Document</code>. Let&#39;s break down the components of this code:</p> <ol> …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def file_size(value): # add this to some file where you can import it from
    limit = 2 * 1024 * 1024
    if value.size > limit:
        raise ValidationError('File Size is larger than 2 MiB.')


def validate_file_extension(value):
    import os
    from django.core.exceptions import ValidationError
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.pdf', '.docx']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file type')


class DocumentFileForm(BootstrapForm, forms.ModelForm):
    doc = forms.FileField(required=False, label='', help_text='', validators=[file_size, validate_file_extension])

    class Meta:
        model = Document
        fields = ('doc',)
Django

django m2m through models

<p>A Django model for a category system. This model defines two classes: <code>Category</code> and <code>ChildCategory</code>. Here&#39;s a brief explanation of each class and its fields:</p> <ol> <li> <p><code>Category</code> class:</p> <ul> …

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
from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=100, unique=True)
    children = models.ManyToManyField('self', through='ChildCategory', symmetrical=False, blank=True)

    class Meta:
        default_related_name = 'categories'
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name


    @property
    def depth_level(self):
        depth = 0
        data = self.targets.all()
        while data:
            for item in data:
                data = item.source.targets.all()
            depth += 1
        return depth

    def breadcrumb(self):
        items = set()
        data = self.targets.all()
        if self.depth_level == 0:
            return items
        for item in data:
            items.add('{} > {}'.format(item.source, self))
        return items


class ChildCategory(models.Model):
    source = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='sources')
    target = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='targets')
Django

import function from differernt app in different project in django

<p>This Python function, named <code>function_importer</code>, is designed to dynamically import a function from a specified module within a given project directory. It performs the import in a way that allows …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import importlib
import sys
import os
from importlib import import_module

def function_importer(project_name, module_name, function_name):
    project_dir = os.path.abspath(
        os.path.join(os.path.dirname(__file__),
                     '..', '..', '..', '{}'.format(
                     project_name)))

    sys.path.insert(1, project_dir)
    p, m = module_name.rsplit('.', 1)
    module = importlib.import_module(p)
    importlib.reload(module)
    try:
        loaded_module = getattr(module, m)
    except AttributeError:
        raise('Add from .{} import * into {}.views.py'.format(
            m, p))
    funct = getattr(loaded_module, function_name)
    return funct