Django

Django

Explore django code snippets and tutorials

Django

Asynchronous management command in django

<p>Asynchronous&nbsp;management command example for django with version 4.2 and for psycopg3&nbsp;</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import asyncio
from django.core.management.base import BaseCommand
from app.models import (
    Model1,
)

class Command(BaseCommand):

    async def import_data_async(self):
        item1, c1_created = await Model1.objects.aupdate_or_create(name="some name")
        item2, c1_created = await Model1.objects.aupdate_or_create(name="some name 2")
        await item1.related.aadd(item2)
 
    def handle(self, *args, **options):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.import_data_async())
        self.stdout.write(self.style.SUCCESS('Data import completed successfully.'))
Django

Django cache decorator per user

<p>This is a Python decorator named `cache_per_user` that can be used to cache the view for each user. It allows you to cache the results of a view function based …

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
def cache_per_user(ttl=None, prefix=None, cache_post=False):
    '''Decorator that caches the view for each user
        * ttl - Cache lifetime, not sending this parameter means the
          cache will last until the server restarts or decides to remove it
        * prefix - Prefix to be used to cache the response. if not
          be informed will use 'view_cache_'+function.__name__
        * cache_post - Informs whether to cache POST requests
        * Cache for anonymous users is shared with everyone
        * The cache key will be one of the possible options:
            '%s_%s'%(prefix, user.id)
            '%s_anonymous'%(prefix)
           'view_cache_%s_%s_%s_%s'%(function.__name__, user.id,args,kwargs)
            'view_cache_%s_anonymous'%(function.__name__)
    '''
    def decorator(function):
        def apply_cache(request, *args, **kwargs):
            if request.user.is_anonymous():
                user = 'anonymous'
            else:
                user = request.user.id

            if prefix:
                base_key = '%s_%s' % (prefix, user)
            else:
                base_key = 'view_cache_%s_%s' % (function.__name__, user)

            # Include function arguments in the cache key
            args_key = '_'.join([str(arg) for arg in args])

            # Include keyword arguments in the cache key
            kwargs_key = '_'.join(['%s=%s' % (key, value) for key, value in kwargs.items()])

            # Generate the cache key
            CACHE_KEY = '%s_%s_%s' % (base_key, args_key, kwargs_key)

            if not cache_post and request.method == 'POST':
                can_cache = False
            else:
                can_cache = True

            if can_cache:
                response = cache.get(CACHE_KEY, None)
            else:
                response = None

            if not response:
                response = function(request, *args, **kwargs)
                if can_cache:
                    cache.set(CACHE_KEY, response, ttl)
            return response

        return apply_cache

    return decorator
Django

Convert request object to dict in django

<p>The provided Python function `request_to_dict(request)` is a utility function used to convert a Django request object (presumably an HTTP request) into a dictionary containing relevant information about the request. It …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def request_to_dict(request):
    # Initialize an empty dictionary
    data = {}

    # Get the GET parameters
    for key in request.GET.keys():
        data[key] = request.GET.get(key)

    # Get the POST parameters
    for key in request.POST.keys():
        data[key] = request.POST.get(key)

    data['method'] = request.method
    data['path'] = request.path
    data['user_agent'] = request.META.get('HTTP_USER_AGENT')
    data['ip_address'] = request.META.get('REMOTE_ADDR')
    return data
Django

Dynamically loop through django model class

<p>Django&#39;s `models` module to get the `ForeignKey` attribute. You then inspect the attributes and methods of the `ForeignKey` class using Python&#39;s built-in `vars()` and `dir()` functions. Let&#39;s go through the …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.db import models
    data = getattr(models, "ForeignKey")
    print(data)
    for attr in vars(data):
        print(f"Attribute: {attr}, Value: {getattr(data, attr)}")

    # Loop through methods
    for method_name in dir(data):
        method = getattr(data, method_name)
        if callable(method):
            print(f"Method: {method_name}")
Django

Loop through django applications dynamically

<p>The code provided appears to be a set of Django views designed to retrieve information about the models and their fields in a Django project. Let&#39;s go through each view …

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
from django.apps import apps
from django.http import JsonResponse

def get_all_models(request):
    all_models = apps.get_models()
    models = []
    for model in all_models:
        # Access model attributes or perform actions with the model
        print(model.__name__)  # Prints the name of the model
        print(model._meta.app_label)  # Prints the app label of the model
        print(model._meta.verbose_name)  # Prints the verbose name of the model
        models.append({"key": str(model._meta.app_label) + '.' + model.__name__, "name":   model.__name__})
    return JsonResponse({"models":models})


def get_apps(request):
    app_configs = apps.get_app_configs()
    apps_data = []
    for app_config in app_configs:
        models = [a for a in app_config.get_models()] 
        if models:
            apps_data.append({"value":app_config.label, "display_name":app_config.name})
    return JsonResponse({"apps":apps_data})


def get_models(request):
    app = request.GET.get('app')
    app_models = [model.__name__ for model in apps.get_app_config(app).get_models()]
    return JsonResponse({"models":app_models})


def get_model_fields(request):
    model_name = request.GET.get('model')
    app_label = request.GET.get('app')
    model_fields = []
    model = apps.get_model(app_label, model_name)
    fields = model._meta.get_fields()
    for field in fields:
        field_name = field.name
        field_type = field.get_internal_type()
        model_fields.append({"field": field_name, "type": field_type})
    return JsonResponse({"fields":model_fields})