Dive into Code

Discover code snippets, tutorials, and programming insights

Django

DRF Allow post put only to superuser

DRF allow post put only to superuser

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from rest_framework.permissions import BasePermission, SAFE_METHODS

class IsSuperUserForWrite(BasePermission):
    """
    Custom permission to only allow superusers to perform POST and PUT requests.
    """
    
    def has_permission(self, request, view):
        # Allow all users to perform SAFE_METHODS (GET, HEAD, OPTIONS)
        if request.method in SAFE_METHODS:
            return True
        
        # Allow only superusers for POST and PUT methods
        if request.method in ['POST', 'PUT']:
            return request.user and request.user.is_superuser
        
        # Allow all other methods (e.g., DELETE) based on other logic if necessary
        return True
Django

Django insert large queryset into m2m

Django insert large queryset into m2m

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db import transaction

# Retrieve the book instance
book = Book.objects.get(id=1)

# Retrieve the large queryset of authors
large_authors_qs = Author.objects.filter(name__startswith='J')

# Define the chunk size
CHUNK_SIZE = 1000

# Add authors in chunks
with transaction.atomic():
    for i in range(0, large_authors_qs.count(), CHUNK_SIZE):
        chunk = large_authors_qs[i:i + CHUNK_SIZE]
        book.authors.add(*chunk)
Django

Django run sql query to other db

Django run sql query to other db

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.db import connections

def dictfetchall(cursor):
    """Return all rows from a cursor as a list of dicts"""
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

def run_raw_query_on_db(db_name,sql_query):
    # Using the cursor to run raw SQL on 'other_db'
    with connections[db_name].cursor() as cursor:
        cursor.execute(sql_query)
        results = dictfetchall(cursor)
    
    return results
Django

Django template tag iterrate object fields dynamically

Django iterrate object fields dynamically

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
import datetime
from decimal import Decimal
from django import template
from django.db import models
from django.urls import reverse,reverse_lazy, NoReverseMatch, resolve
from django.apps import apps
from django.db.models.fields.files import ImageFieldFile, FileField
from django.db.models.fields import DateTimeField
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()


@register.simple_tag
def display_data(object):
    items = {}
    for field in object._meta.fields:
        print(type(field), field.name)
        value = getattr(object,field.name)
        if isinstance(value, Decimal):
            value = round(value,0)
        elif isinstance(value, datetime.datetime):
            format = '%Y-%m-%d %H:%M:%S'
            print(format)
            # applying strftime() to format the datetime
            string = value.strftime(format)
            value = str(string)
        elif isinstance(field, models.ForeignKey):
            related_object = value  # This is the related object
            if related_object:  # Check if the related object exists
                value = str(related_object) 
        items[field.name] = value
    return items