Dive into Code

Discover code snippets, tutorials, and programming insights

jQuery

Pass search string on datatables on load

Pass search string on datatables on load

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<table id="myTable">
  <!-- Table contents go here -->
</table>

<!-- JavaScript code -->
<script>
$(document).ready(function() {
  // Initialize DataTables
  var table = $('#myTable').DataTable();

  // Get the search query from a search input field, for example
  var searchQuery = $('#searchInput').val();

  // Apply the search query to the DataTables search
  table.search(searchQuery).draw();
});
</script>
Python

Generate a string based on permutations

<p>The provided code generates all possible permutations of the elements in the list `my_list` and then concatenates each permutation into a single string. Let&#39;s understand the code step by step:</p> …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import itertools

# Define the list of elements
my_list = ['a', 'b', 'c']

# Generate permutations of the list
permutations = list(itertools.permutations(my_list))

# Concatenate elements from each permutation into a string
result = ''
for perm in permutations:
    result += ''.join(perm)

print(result)
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})
Python

Write python response data to json file

<p>This Python code is a script that sends an HTTP GET request to a URL (in this case, &#39;<a href="https://google.com/" target="_new">https://google.com</a>&#39;) using the <code>requests</code> library and saves the response data …

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
import json
import requests

url = 'https://google.com'
headers = {}

response = requests.get(url, headers=headers)
response_headers = response.headers['Content-Type']

if response.status_code == 200:
    if 'json' in response_headers:
        filetype = 'json'
        try:
            content = response.json()
        except json.JSONDecodeError:
            print("Error: Response content is not in JSON format.")
            content = None
    else:
        filetype = 'txt'  # You can set a default extension for other content types.
        content = response.content

    filename = "response_data"
    with open(f"{filename}.{filetype}", 'w', encoding='utf-8') as f:
        if content is not None:
            if filetype == 'json':
                json.dump(content, f, ensure_ascii=False, indent=4)
            else:
                f.write(content)
    print(f"Response saved to {filename}.{filetype}")
else:
    print(f"Failed to fetch data. Status Code: {response.status_code}")