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.

Categories
Python Answers

How to fix the Python Django MultiValueDictKeyError error?

To fix the Python Django MultiValueDictKeyError error, we use the dictionary get method to get the dict value and return a default if the dict key doesn’t exist.

For instance, we write

is_private = request.POST.get('is_private', False)

to call get on request.POST to get the is_private dict value from the POST request payload.

And if is_private wasn’t sent, then we return False.

Categories
Python Answers

How to handle multiple forms on one page in Python Django?

To handle multiple forms on one page in Python Django, we can set the forms to use in our views.

For instance, we write

if request.method == 'POST':
    bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
    if bannedphraseform.is_valid():
        bannedphraseform.save()
else:
    bannedphraseform = BannedPhraseForm(prefix='banned')

if request.method == 'POST' and not bannedphraseform.is_valid():
    expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
    bannedphraseform = BannedPhraseForm(prefix='banned')
    if expectedphraseform.is_valid():
        expectedphraseform.save()

else:
    expectedphraseform = ExpectedPhraseForm(prefix='expected')

in our view to set different forms to use according to different conditions.

We use if statements to check request methods and form validation to assign which form to render in the page.