Skip to content

Instantly share code, notes, and snippets.

@maddrum
maddrum / django_test_read_file
Last active February 13, 2024 08:27
Django manually assign file to model
def test_picture_path_is_correct(self):
obj = self.create_obj()
abs_path = os.path.join(settings.TEST_MEDIA_ASSETS_FOLDER, 'profile_picture_1280.png')
obj.picture.save('filename.png', ImageFile(open(abs_path, 'rb'))) # this line reads image and store it as binary
obj.save()
self.assertTrue(os.path.isfile(obj.picture.path))
@maddrum
maddrum / type_var_sample.py
Last active December 5, 2023 14:54
TypeVars
import typing
from abc import ABC
_th_base = typing.TypeVar('_th_base', bound='BaseKlass')
class BaseKlass(ABC):
def __init__(self, selected_topic):
self.selected_topics = selected_topics
@maddrum
maddrum / test_template_tags.py
Last active November 21, 2023 06:49
Django test templatetags
import datetime
from django.template import Template
from django.template.context import Context, RequestContext
def test_is_today(self):
template = Template('{% load sample_tags %} {{ date|is_today }}')
rendered = template.render(Context({'date': self.today}))
self.assertEqual(str(True), str(rendered).strip())
rendered = template.render(Context({'date': self.today + datetime.timedelta(days=1)}))
self.assertEqual(str(False), str(rendered).strip())
from django.test import TestCase
from path.to.abstract.model import SomeAbstractModel
class SampleModel(SomeAbstractModel):
class Meta:
# app_label is needed in cases where tests are in folder of project to be able to find this model
app_label = 'app.name.of.where.abstract.model.is.defined'
@maddrum
maddrum / django_formset_custom_model_manager.txt
Last active January 3, 2023 19:59
Django formset with custom model manager
from django.forms import BaseModelFormSet
from app.companies.models import CompanyBranchPaymentOptions
class PaymentsBaseFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__full_id_queryset = CompanyBranchPaymentOptions.objects.get_full_queryset()
@maddrum
maddrum / it-is-pythonic.py
Created October 13, 2022 06:57
Why know it is Python when....
value_list = [
{
'name': 'a',
'value': '1',
},
{
'name': 'a',
'value': '2',
},
{
@maddrum
maddrum / Django admin Inline models with custom model manager - wrong querysetfix
Last active January 4, 2023 08:54
Django admin Inline models with custom model manager - wrong querysetfix
# bug described here - https://code.djangoproject.com/ticket/33813
----
# Definitions
# models
class ReviewsModelManager(models.Manager):
def get_queryset(self):
qs = super().get_queryset()
qs = qs.filter(published=True)
return qs
import logging
import time
logger = logging.getLogger('MyLogger')
def measure_run_time(func):
def wrapper(*args, **kwargs):
total_start_time = time.time_ns()
def decorator(func):
"""This is a decorator function. It takes some function as a parameter, 'wraps it' in code
and RETURNs wrapped function
This is a way to add functionality without changing base code"""
def wrap(text='this is base function'):
print('this is pre-function')
func(text)
print('this is post func')
"""getters, setters and property decorators examples
Used to get and set protected variables(starts with _)
using property makes all code call getter and setter functions when rear and write do this class protected variable"""
class AddTesterToString:
def __init__(self, input_string):
self.input_string = input_string
# def getter function - gets _protected variable