Categories
Python Answers

How to use Python Django time/date widgets in custom form?

To use Python Django time/date widgets in custom form, we can use AdminTimeWidget and AdminDateWidget and AdminSplitDateTime.

For instance, we write

from django import forms
from my_app.models import Product
from django.contrib.admin import widgets                                       

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['mydate'].widget = widgets.AdminDateWidget()
        self.fields['mytime'].widget = widgets.AdminTimeWidget()
        self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()

to add the mydate, mytime, and mydatetime fields and set them to AdminDateWidget, AdminTimeWidget, and AdminSplitDateTime to use them as date or time widgets in our form.

Categories
Python Answers

How to fix the “Too many values to unpack” Exception in Python?

To fix the "Too many values to unpack" Exception in Python, we should unpack only the number of items listed in the tuple.

For instance, we write

def returnATupleWithThreeValues():
    return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c

to unpack all 3 items by assigning the tuple returned by returnATupleWithThreeValues to a, b, and c.

But if we write

def returnATupleWithThreeValues():
    return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b

then we’ll get the error since we only unpacked 2 of the items and there’re 3 returned.

Categories
Python Answers

How to log all SQL queries with Python Django?

To log all SQL queries with Python Django, we can set the LOGGING variable in settings.py.

For instance, we write

LOGGING = {
    'version': 1,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
            'handlers': ['console'],
        }
    }
}

to set LOGGING to a dictionary with loggers set to a dictionary with level set to DEBUG and handlers set to ['console'] to log SQL queries to the console.

Categories
Python Answers

How to add login with email with Python Django?

To add login with email with Python Django, we can add an EmaolFoeld with unique set to True.

For instance, we write

class MyUser(AbstractUser):
    USERNAME_FIELD = 'email'
    email = models.EmailField(_('email address'), unique=True)
    REQUIRED_FIELDS = []

to create the email EmailField that has unique set to True to make all the values of it unique.

And then we set USERNAME_FIELD to 'email' to make the username field the email field we just created.

Then we can use authenticate(email=email, password=password) to authenticate.

Categories
Python Answers

How to with upload_to determined at runtime with a Python Django FileField?

To with upload_to determined at runtime with a Python Django FileField, we can set the upload_to path dynamically in a FileField.

For instance, we write

def content_file_name(instance, filename):
    return '/'.join(['content', instance.user.username, filename])

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=content_file_name)

to create the content_file_name function to compute the path of the file path to save to return it.

And then we create the file FileField in the Content model by setting the upload_to argument to the content_file_name function so that it’s run at runtime to determine the upload path.