# Example model
class Category(models.Model):
parent = models.ForeignKey('Category',
on_delete=models.CASCADE,
verbose_name=_('Parent'),
related_name='children',
blank=True,
null=True)
title = models.CharField(_('Title'), max_length=64, unique=True)
slug = models.SlugField(max_length=50)
objects = CategoryManager()
# Manager with method to build tree using directed graph
class CategoryManager(models.Manager):
def _traverse(self, hierarchy, graph, items):
for item in items:
hierarchy.append(item)
hierarchy.append(self._traverse([], graph, graph[item.title]))
return hierarchy
def as_tree(self):
"""Returns FK hierarchy in form of nested lists."""
qs = super().get_queryset().exclude(
title='Unassigned'
).select_related('parent')
roots = []
children = []
for item in qs:
roots.append(item) if item.parent is None else children.append(item)
graph = {item.title: set() for item in qs}
sorted_children = sorted(children, key=lambda x: x.parent.title)
grouped = groupby(children, key=lambda x: x.parent.title)
for title, group in grouped:
graph[title].update(group)
return self._traverse([], graph, roots)
# To render in template in form of simple nested unordered list use built-in filter:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list
{{ tree|unordered_lsit }}
import winreg
winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\\Uninstall\{F57F0CBD-3260-4021-83E6-CA2224672634$}', 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ))
import pytest
@pytest.fixture()
def fixture1():
print "Fixture 1"
@pytest.fixture()
def fixture2():
print "Fixture 2"
import pytest
def skip_non_matching_url(option):
return pytest.mark.skipif(
not getattr(pytest.config.option, option, None),
reason="Url doesn't match command line option"
)
@skip_non_matching_url("url2")
def test_my_url2(fixture2):
print "Test my url2"
@skip_non_matching_url("url1")
def test_my_url1(fixture1):
print "Test my ulr1"
$ python -m pytest -vs --url1 ya.ru
collected 2 items
test_something.py::test_my_url2 SKIPPED
test_something.py::test_my_url1 Fixture 1
Test my ulr1
PASSED
$ python -m pytest -vs --url2 ya.ru
collected 2 items
test_something.py::test_my_url2 Fixture 2
Test my url2
PASSED
test_something.py::test_my_url1 SKIPPED
import pytest
@pytest.mark.url2
def test_my_url2(fixture2):
print "Test my url2"
@pytest.mark.url1
def test_my_url1(fixture1):
print "Test my ulr1"
$ python -m pytest -vs -m url2
collected 2 items
test_something.py::test_my_url2 Fixture 2
Test my url2
PASSED
$ python -m pytest -vs -m url1
collected 2 items
test_something.py::test_my_url1 Fixture 1
Test my ulr1
PASSED
''.isalpha() # False
' '.isalpha() # False
'!@#'.isalpha() # False
'abc'.isalpha() # True
'123'.isalpha() # False
'abc123'.isalpha() # False
'абв'.isalpha() # True
'абв123'.isalpha() # False
def my_comb(pattern, r):
comb_list = combinations(pattern, r)
for c in comb_list:
yield ''.join(x if x in c else '-' for x in pattern)
>>> list(my_comb('ABC', 2))
['AB-', 'A-C', '-BC']
>>> list(my_comb('ABCDE', 3))
['ABC--', 'AB-D-', 'AB--E', 'A-CD-', 'A-C-E', 'A--DE', '-BCD-', '-BC-E', '-B-DE', '--CDE']
>>> import lxml.etree
>>> doc = """
... <?xml version="1.0" encoding="ANSI" ?>
... <data>
... <items>
... <item name="item1">1</item>
... <item name="item2">2</item>
... <item name="item3">3</item>
... <item name="item4">4</item>
... </items>
... </data>
... .----------------------------------------------------------
... """
>>> parser = lxml.etree.XMLParser(recover=True)
>>> tree = lxml.etree.fromstring(doc, parser)
>>> [element.text for element in tree.iter('item')]
['1', '2', '3', '4']
>>> import xml.etree.ElementTree as ET
>>> doc = """
... <?xml version="1.0" encoding="ANSI" ?>
... <data>
... <items>
... <item name="item1">1</item>
... <item name="item2">2</item>
... <item name="item3">3</item>
... <item name="item4">4</item>
... </items>
... </data>
... .----------------------------------------------------------
... """
>>> tree = ET.fromstring(doc.strip('\n-.'))
>>> [element.text for element in tree.iter('item')]
['1', '2', '3', '4']
К сожалению не помогло, ошибка та же:
class EventGETSerializer(serializers.ModelSerializer):
place = PlaceSerializer(read_only=True)
class Meta:
model = Event
fields = ('id', 'title', 'description', 'price', 'place', 'link', 'date', 'time')
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('id', 'title', 'description', 'price', 'place', 'link', 'date', 'time')
from rest_framework import permissions
class EventList(generics.ListCreateAPIView):
queryset = Event.objects.all()
def get_serializer_class(self):
if self.request.method in permissions.SAFE_METHODS:
return EventGETSerializer
else:
return EventSerializer
from rest_framework.permissions import SAFE_METHODS
class EventSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
request = kwargs.get('context', {}).get('request')
if request is not None and request.method not in SAFE_METHODS:
self.Meta.depth = 0
else:
self.Meta.depth = 1
super().__init__(*args, **kwargs)
class Meta:
model = Event
fields = ('id', 'title', 'description', 'price', 'place', 'link',
'date', 'time')
к тому же delete_model как и save нельзя использовать для блокирования удаления объекта, только для добавления действий до и после удаления.
from django.contrib import messages
def delete_model(self, request, obj):
"""Если какая-то проверка успешна - удалить объект, если нет, то показать сообщение об ошибке."""
if check_permission(obj):
return super().delete_model(request, obj)
# При следующем запросе захватываем только ошибки.
# Так после нажатия на кнопку удаления не будет захвачено ложное сообщение
# об успешном удалении.
messages.set_level(request, messages.ERROR)
message = "You cant delete this!"
# Посылаем свое сообщение об ошибке.
self.message_user(request, message, level=messages.ERROR)
from rest_framework.response import Response
class TrainingDetailAPIView(RetrieveAPIView):
queryset = Training.objects.all()
serializer_class = TrainingSerializer
lookup_field = 'slug'
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance, fields=('title', 'description'))
return Response(serializer.data)
class TrainingDetailAPIView(RetrieveAPIView):
queryset = Training.objects.all()
serializer_class = TrainingSerializer
lookup_field = 'slug'
def get_serializer(self, *args, **kwargs):
kwargs['fields'] = ('title', 'description')
return super().get_serializer(*args, **kwargs)
class ShowFieldsMixin:
def get_serializer(self, *args, **kwargs):
if getattr(self, 'fields_to_show', None) is not None:
kwargs['fields'] = self.fields_to_show
return super().get_serializer(*args, **kwargs)
class TrainingDetailAPIView(ShowFieldsMixin, RetrieveAPIView):
queryset = Training.objects.all()
serializer_class = TrainingSerializer
lookup_field = 'slug'
fields_to_show = ('title', 'description')
class TrainingListAPIView(ShowFieldsMixin, ListAPIView):
# bla-bla-bla
serializer_class = TrainingSerializer
fields_to_show = ('name', 'description', 'url', 'slug')
table = [
['header1', 'header2', 'header3', 'header4'],
['value1.1', 'value2.1', 'value3.1', 'value4.1'],
['value1.2', 'value2.2', 'value3.2', 'value4.2']
]
table = [('header1', 'header2', 'header3', 'header4')]
table += Model.objects.all().values_list('value1', 'value2', 'value3', 'value4')
context['table'] = table
<table>
{% for v1, v2, v3, v4 in table %}
{% if forloop.first %}
<tr>
<th>{{ v1 }}</th>
<th>{{ v2 }}</th>
<th>{{ v3 }}</th>
<th>{{ v4 }}</th>
</tr>
{% else %}
<tr>
<td>{{ v1 }}</td>
<td>{{ v2 }}</td>
<td>{{ v3 }}</td>
<td>{{ v4 }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
function drawChart(chartData, lineChartId) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Time of Day');
data.addColumn('number', 'KWR');
data.addColumn('number', 'BSR');
data.addRows(chartData);
var options = {
colors: ['#000000','#ff9000'],
hAxis: {
format: 'M/d/yy',
gridlines: {count: 10}
},
vAxis: {
direction: -1
}
};
var chart = new google.visualization.LineChart(document.getElementById(lineChartId));
chart.draw(data, options);
}
>>> from email.header import decode_header
>>> s = '=?UTF-8?B?0KHQsdC10YDQsdCw0L3QuiDQntC90LvQsNC50L0uINCe0LTQvdC+0YDQsNC3?='
>>> bytes, encoding = decode_header(s)[0]
>>> bytes.decode(encoding)
'Сбербанк Онлайн. Однораз'