Categories
Python Answers

How to filter objects for count annotation in Python Django?

Sometimes, we want to filter objects for count annotation in Python Django.

In this article, we’ll look at how to filter objects for count annotation in Python Django.

How to filter objects for count annotation in Python Django?

To filter objects for count annotation in Python Django, we call annotate with the field argument set to the count result.

For instance, we write

from django.db.models import Q, Count
events = Event.objects.annotate(
    paid_participants=Count('participants', filter=Q(participants__is_paid=True))
)

to call annotate with the paid_participants argument set to the aggregation result of getting the count of the participants field values with Count.

We call Count with filter to do the filtering when aggregating the count.

Conclusion

To filter objects for count annotation in Python Django, we call annotate with the field argument set to the count result.

Categories
Python Answers

How to setup of Python logging in Django?

Sometimes, we want to setup of Python logging in Django.

In this article, we’ll look at how to setup of Python logging in Django.

How to setup of Python logging in Django?

To setup of Python logging in Django, we set the LOGGING variable in settings.py.

For instance, we write

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        }
    }
}

in settings.py to set the settings for logging.

handlers is a dict with the settings for logging various kinds of events.

And we add the handler names into the handlers setting in loggers.

class is the path to the logger class.

level is the logging level.

Conclusion

To setup of Python logging in Django, we set the LOGGING variable in settings.py.

Categories
Python Answers

How to set up a PostgreSQL database in Python Django?

Sometimes, we want to set up a PostgreSQL database in Python Django.

In this article, we’ll look at how to set up a PostgreSQL database in Python Django.

How to set up a PostgreSQL database in Python Django?

To set up a PostgreSQL database in Python Django, we add the psycopg2 package and add some settings into settings.py.

We run

pip install psycopg2

to install psycopg2.

Then in settings.py, we write

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

to set the DATABASE variable to a dict with the settings.

USER and PASSWORD ahs the user and password.

HOST and PORT has the URL and port of the database server.

Conclusion

To set up a PostgreSQL database in Python Django, we add the psycopg2 package and add some settings into settings.py.

Categories
Python Answers

How to override widget in a Python Django ModelForm?

Sometimes, we want to override widget in a Python Django ModelForm.

In this article, we’ll look at how to override widget in a Python Django ModelForm.

How to override widget in a Python Django ModelForm?

To override widget in a Python Django ModelForm, we can set the widgets field to a dict with the field overrides.

For instance, we write

from django.forms import ModelForm, Textarea
from myapp.models import Author

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

to create the AuthorForm model form class with a few fields.

We set the widgets field to a dict with the name field overridden with a Textarea with 80 columns and 20 rows.

Conclusion

To override widget in a Python Django ModelForm, we can set the widgets field to a dict with the field overrides.

Categories
Python Answers

How to split string to array with Python Django templates?

Sometimes, we want to split string to array with Python Django templates.

In this article, we’ll look at how to split string to array with Python Django templates.

How to split string to array with Python Django templates?

To split string to array with Python Django templates, we can create our own model method to do the splitting.

For instance, we write

class Game(models.Model):
    #...
    def screenshots_as_list(self):
        return self.screenshots.split('\n')

to create the Game model with the screenshots_as_list method to return the screenshots string field split into an array by the newline.

And then in our template, we use it by writing

{% for screen in game.screenshots_as_list %}
    {{ screen }}<br>
{% endfor %}

Conclusion

To split string to array with Python Django templates, we can create our own model method to do the splitting.