Django

Django

Explore django code snippets and tutorials

Django

Django model self many-to-many relation

<p>The provided code defines two classes: <code>Folder</code> and <code>FolderParent</code>. Let&#39;s go through each class and understand their functionalities:</p> <ol> <li> <p><code>Folder</code> class:</p> <ul> <li>It inherits from the <code>Timestamped</code> class (not …

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Folder(Timestamped):
    name = models.CharField(max_length=50)
    depth = models.PositiveIntegerField(default=0)
    parents = models.ManyToManyField("self", through='FolderParent',
                                      through_fields=('source', 'target'),
                                      symmetrical=False, blank=True)



    class Meta:
        default_related_name = 'folders'
        verbose_name = 'folder'
        verbose_name_plural = 'folders'

    def __str__(self):
        return f"{self.name}"

    def get_depth(self):
        """
        Recursively calculates the depth of the folder in the tree structure.
        """
        depth = 0
        # Traverse up the tree to the root node
        parent_folders = self.parents.all()
        while parent_folders:
            depth += 1
            parent_folder = parent_folders.first()
            parent_folders = parent_folder.parents.all()
        if depth != self.depth:
            self.depth = depth
            self.save()
        return depth

    def get_ancestors(self):
        """
        Recursively gets a list of ancestor folders in the tree structure.
        """
        ancestors = []
        parent_folders = self.parents.all()
        while parent_folders:
            parent_folder = parent_folders.first()
            ancestors.append(parent_folder)
            parent_folders = parent_folder.parents.all()
        return reversed(ancestors)

    def get_breadcrumb(self):
        """
        Returns a list of ancestor folders and the current folder, 
        representing the breadcrumb for the current folder.
        """
        breadcrumb = list(self.get_ancestors())
        breadcrumb.append(self)
        return breadcrumb


class FolderParent(Timestamped):
    source = models.ForeignKey(Folder, on_delete=models.CASCADE,
                               related_name='folder_parent')
    target = models.ForeignKey(Folder, on_delete=models.CASCADE,
                               related_name='folder_child')

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['source', 'target'], name="folderparent")
        ]
        indexes = [
            models.Index(fields=['source', 'target']),
        ]
Django

django delete model function

<p>This Django view function is designed to handle DELETE requests and delete an item from a database based on the provided parameters. Let&#39;s go through the code step by step …

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
from django.http import JsonResponse, HttpResponseBadRequest, Http404
from django.apps import apps
from django.views.decorators.http import require_http_methods

@require_http_methods(["DELETE"])
def delete_item(request):
    item_id = request.GET.get('id')
    if not item_id:
        return JsonResponse({'error': 'Missing ID parameter.'}, status=400)

    model_name = request.GET.get('model')
    app_name = request.GET.get('app')

    if not model_name or not app_name:
        return JsonResponse({'error': 'Missing model or app parameter.'}, status=400)

    try:
        model_obj = apps.get_model(app_label=app_name, model_name=model_name)
    except LookupError:
        return JsonResponse({'error': 'Invalid model or app parameter.'}, status=400)

    try:
        item = model_obj.objects.get(id=item_id)
        item.delete()
        return JsonResponse({'message': 'Item deleted successfully.'}, status=200)
    except model_obj.DoesNotExist:
        raise Http404("Item does not exist.")
Django

Django settings for vscode

django settings for vscode

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
from vscode market place install  python,django,beautify

in your python virtual environment install packages

autopep8
pylint
pylint-django


in vscode  settings.json add 

{
    "emmet.includeLanguages": {
        "django-html": "html"
    },
    "python.PythonPath": ".venv\\scripts\\python.exe",
    "editor.formatOnSave": true,
    "python.formatting.provider": "autopep8",
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "files.associations": {
        "**/templates/*.html": "django-html",
        "**/templates/*": "django-txt",
        "**/requirements{/**,*}.{txt,in}": "pip-requirements",
        "*.html": "html"
    },
}
Django

django template tag for boolean image

<p>This code is a custom Django template tag named <code>get_boolean_img</code>. It&#39;s used to render a specific HTML icon based on a boolean value (True or False).</p> <p>&nbsp;</p> <ol> <li> <p>The …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()


@register.simple_tag
def get_boolean_img(value):
    if value:
        return format_html(mark_safe('<i class="bi bi-check-lg"></i>'))
    return format_html(mark_safe('<i class="bi bi-x"></i>'))
Django

example gulpfile to work with django

<p>This is a Gulp configuration file used to automate various tasks for a web development project. It utilizes various Gulp plugins to minify CSS and JavaScript files, concatenate them, and …

javascript
 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const { parallel, src, dest, watch, series } = require('gulp');
const gulp = require("gulp");
let rename = require("gulp-rename");
const cleanCSS = require('gulp-clean-css');
const minify = require('gulp-minify');
let wrap = require('gulp-wrap');
let declare = require('gulp-declare');
let concat = require('gulp-concat');
let exec = require('child_process').exec;
const browsersync = require('browser-sync').create();
let spawn = require('child_process').spawn;

function css(){
  return gulp.src([
        './static/src/css/*.css'])
     .pipe(concat('site.css'))
     .pipe(cleanCSS({compatibility: 'ie8'}))
     .pipe(rename({extname:'.min.css'}))
     .pipe(gulp.dest('./static/build/css'))
     .pipe(browsersync.reload({
       stream: true
     }))
}

function vendor(){
  return gulp.src([
        './static/src/js/jquery-3.6.0.min.js',
        './static/src/js/popper.min.js',
        './static/src/js/bootstrap.min.js',
        './static/src/js/django_ajax.js',
        './static/src/js/site.js',
      ])
     .pipe(concat('site.js'))
     .pipe(minify())
     .pipe(gulp.dest('./static/build/js'))
     .pipe(browsersync.reload({
       stream: true
      }))
}


function browsersyncServe(cb){
  browsersync.init({
          notify: false,
          proxy: "localhost:8000"
  });
  browsersync.watch('static/src/css/**/*.css', series(css));
  browsersync.watch('static/src/js/**/*.js', series(vendor));
  browsersync.watch('templates/**/*.html', browsersync.reload);
  browsersync.watch('templates/*.html', browsersync.reload);
  cb();
}


function runServer(){
  var cmd = spawn('venv/Scripts/python.exe', ['manage.py', 'runserver'], {stdio: 'inherit'});
  cmd.on('close', function(code) {
    console.log('runServer exited with code ' + code);
    cb(code);
  });
}

exports.css = css;
exports.vendor = vendor;
exports.runServer = runServer;
exports.browsersyncServe = browsersyncServe;
exports.default = parallel(css, vendor, runServer, browsersyncServe);