Categories
Python Answers

How to override save for model with Python Django?

To override save for model with Python Django, we can add the save method into our model class.

For instance, we write

class Model(model.Model):
    _image=models.ImageField(upload_to='folder')
    thumb=models.ImageField(upload_to='folder')
    description=models.CharField()

    def set_image(self, val):
        self._image = val
        self._image_changed = True

        # Or put whole logic in here
        small = rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)

    def get_image(self):
        return self._image

    image = property(get_image, set_image)

    def save(self, *args, **kwargs):
        if getattr(self, '_image_changed', True):
            small=rescale_image(self.image,width=100,height=100)
            self.image_small=SimpleUploadedFile(name,small_pic)
        super(Model, self).save(*args, **kwargs)

to add the save method that calls the model.Model class’ save method with

super(Model, self).save(*args, **kwargs)

after we do the things we want to do in it.

Categories
Python Answers

How to convert Python Django Model object to dict with all of the fields intact?

To convert Python Django Model object to dict with all of the fields intact, we can use the queryset’s values().first method.

For instance, we write

type(o).objects.filter(pk=o.pk).values().first()

to create a queryset with

type(o).objects.filter(pk=o.pk)

then we get the values returned by the query set with values.

And then we return the first item returned by values with the first method.

first returns the item as a dictionary.

Categories
Python Answers

How to convert JSON data into a Python object?

To convert JSON data into a Python object?, we can use the SimpleNamespace class.

For instance, we write

import json
from types import SimpleNamespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
print(x.name, x.hometown.name, x.hometown.id)

to call json.loads to load the data into a dictionary.

And then we set object_hook to a lambda function that takes dictionary d and convert it to an object with the SimpleNamespace class.

Then we can access the data values from the object with

x.name, x.hometown.name, x.hometown.id

as we have in print.

Categories
Python Answers

How to retrieve parameters from a URL with Python?

To retrieve parameters from a URL with Python, we use urlparse from urllib.parse.

For instance, we write

from urllib.parse import urlparse
from urllib.parse import parse_qs

url = 'https://www.example.com/some_path?some_key=some_value'
parsed_url = urlparse(url)
captured_value = parse_qs(parsed_url.query)['some_key'][0]

print(captured_value)

to call parse_qs on the parsed_url object returned by urlparse to get the query string.

And then we get the query value from the dict returned by parse_qs.

parsed_url.query has the query string of the URL.

Categories
Python Answers

How to get a list of Python Pytz Timezones?

To get a list of Python Pytz Timezones, we can use pytz.all_timezones.

For instance, we write

import pytz
pytz.all_timezones

to get a list of all timezones with pytz.all_timezones.