Python get base classes of object
Python get base classes of object
1 | object.__class__.__bases__
|
Discover code snippets, tutorials, and programming insights
Python get base classes of object
1 | object.__class__.__bases__
|
Python get object class name
1 | object.__class__.__name__
|
Django mixin for reusable absolute url method
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 | from django.urls import reverse
class AbsoluteUrlMixin:
'''
Example:
class Category(AbsoluteUrlMixin, models.Model):
name = models.CharField(max_length=100)
url_name = 'update'
I use the convention as pattern:
app_name.model_name.detail
'''
def get_absolute_url(self):
kwargs = {}
slug = hasattr(self, 'slug')
url_name = hasattr(self, 'url_name')
kwargs['pk'] = self.pk
if not url_name:
url_name = 'detail'
if slug:
kwargs['slug'] = self.slug
return reverse('{}.{}.{}'.format(self._meta.app_label,
self.__class__.__name__.lower(), url_name), kwargs=kwargs)
|
Convert linestring string into linestring object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from django.contrib.gis.geos import GEOSGeometry, GEOSException
def convert_linestring(data):
'''
Get the route from the array
Convert the route in LineString object
'''
linestring_raw = ''
k = 0
for i in data:
k += 1
if i in linestring_raw:
pass
else:
linestring_raw += i
linestring_raw += ','
wkt = "LineString({})".format(linestring_raw).replace(',)', ')')
try:
linestring = GEOSGeometry(wkt)
linestring.srid = 4326
except GEOSException:
linestring = None
return linestring
|
Convert polygon string into polygon object
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 | from django.contrib.gis.geos import GEOSGeometry, GEOSException
def convert_polygon(data):
'''
Get the polygon from the array
Convert the polygon in Polygon object
'''
polygon_raw_string = ''
for i in data:
if i in polygon_raw_string:
pass
else:
polygon_raw_string += i
polygon_raw_string += ' , '
polygon_raw_string += data[0]
wkt = "POLYGON(("+polygon_raw_string+"))"
try:
polygon = GEOSGeometry(wkt)
polygon.srid = 4326
except GEOSException:
polygon = None
return polygon
|