Categories
Python Answers

How to filter query objects by date range in Python Django?

To filter query objects by date range in Python Django, we can use the filter method.

For instance, we write

Sample.objects.filter(date__range=["2021-01-01", "2021-01-31"])

to call objects.filter with the date__range parameter set to a list with the date range with the strings as the date values.

date is the column name we’re filtering by.

Categories
Python Answers

How to add Python Django MEDIA_URL and MEDIA_ROOT?

To add Python Django MEDIA_URL and MEDIA_ROOT, we add them to our URL config to serve uploaded files when developing our app locally.

For instance, we write

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

to call static with settings.MEDIA_URL and document_root=settings.MEDIA_ROOT to add the route to expose the uploaded files when developing our app locally.

Categories
Uncategorized

How to temporarily disable a foreign key constraint in MySQL?

To temporarily disable a foreign key constraint in MySQL, we set the FOREIGN_KEY_CHECKS environment variable.

To disable it, we run

SET FOREIGN_KEY_CHECKS=0;

to set FOREIGN_KEY_CHECKS to 0.

And then we enable it again by running

SET FOREIGN_KEY_CHECKS=1;
Categories
Python Answers

How to enable CORS on Python Django REST Framework?

To enable CORS on Python Django REST Framework, we add the django-cors-headers package.

To install it, we run

python -m pip install django-cors-headers

Then we add

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

in INSTALLED_APPS.

And add

MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...,
]

in middleware.

Then we add

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
]

in our Django’s config to allow CORS in the hosts listed.

Categories
Python Answers

How to override and extend basic Python Django admin templates?

To override and extend basic Python Django admin templates, we can use the extends helper.

For instance, we write

{% extends "admin:admin/index.html" %}

{% block sidebar %}
    {{block.super}}
    <div>
        <h1>Extra links</h1>
        <a href="/admin/extra/">My extra link</a>
    </div>
{% endblock %}

to use extends with the admin template file we want to extend from.

And then we add our own items below the extends block.