How to see the raw SQL queries Django is running?

See the docs FAQ: “How can I see the raw SQL queries Django is running?” django.db.connection.queries contains a list of the SQL queries: from django.db import connection print(connection.queries) Querysets also have a query attribute containing the query to be executed: print(MyModel.objects.filter(name=”my name”).query) Note that the output of the query is not valid SQL, because: “Django … Read more

Can I access constants in settings.py from templates in Django?

If it’s a value you’d like to have for every request & template, using a context processor is more appropriate. Here’s how: Make a context_processors.py file in your app directory. Let’s say I want to have the ADMIN_PREFIX_VALUE value in every context: from django.conf import settings # import the settings file def admin_media(request): # return … Read more

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions : Access-Control-Allow-Origin wildcard subdomains, ports and protocols Cross Origin Resource Sharing with Credentials Besides * … Read more

How to convert JSON data into a Python object?

UPDATE With Python3, you can do it in one line, using SimpleNamespace and object_hook: import json from types import SimpleNamespace data=”{“name”: “John Smith”, “hometown”: {“name”: “New York”, “id”: 123}}” # Parse JSON into an object with attributes corresponding to dict keys. x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d)) print(x.name, x.hometown.name, x.hometown.id) OLD ANSWER (Python2) In Python2, … Read more

What’s the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you’re going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you’re going to get a “set” of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by “reverse ForeignKeys” … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)