Categories
Python Answers

How to show form with error message if not valid with Python Django Forms?

To show form with error message if not valid with Python Django Forms, we can use form.errors to check for errors.

For instance, we write

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

to use form.errors in the if block to check for errors.

If there’re any errors, then we loop through the form errors and render the field.errors with a for loop.

And we render non-field errors by looping through form.non_field_errors with another for loop.

Categories
Python Answers

How to group by date (day, month, year) with Python Django?

To group by date (day, month, year) with Python Django, we can use the values method.

For instance, we write

from django.db.models.functions import TruncMonth
from django.db.models import Count

Sales.objects
    .annotate(month=TruncMonth('created')) 
    .values('month')                        
    .annotate(c=Count('id'))                
    .values('month', 'c')              

to call values with 'month' to group by month in our query,

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.