When using a new library such as django, you can improve you developer effectiveness by being familiar with the most common questions that come up when using the python django library. Using the Stack Overflow Data Explorer tool, we’ve determined the top 10 most popular django questions & answers by daily views on Stack Overflow to to be familiar with. Check out the top 10 django questions & answers below:

Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!

Buy Now On Amazon

1. ‘pip’ is not recognized as an internal or external command?

You need to add the path of your pip installation to your PATH system variable. By default, pip is installed to C:\Python34\Scripts\pip (pip now comes bundled with new versions of python), so the path “C:\Python34\Scripts” needs to be added to your PATH variable.

To check if it is already in your PATH variable, type echo %PATH% at the CMD prompt

To add the path of your pip installation to your PATH variable, you can use the Control Panel or the setx command. For example:

setx PATH "%PATH%;C:\Python34\Scripts"

Note:
According to the official documentation, “[v]ariables set with setx variables are available in future command windows only, not in the current command window”. In particular, you will need to start a new cmd.exe instance after entering the above command in order to utilize the new environment variable.

Thanks to Scott Bartell for pointing this out.

2. How to fix error “error: command errored out with exit status 1: python.” when trying to install django-heroku using pip?

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

3. Pylint “unresolved import” error in visual studio code?

The accepted answer won’t fix the error when importing own modules.

Use the following setting in your workspace settings .vscode/settings.json:

"python.autoComplete.extraPaths": ["./path-to-your-code"],

Reference: Troubleshooting, Unresolved import warnings

4. Where does pip install its packages?

pip show <package name> will provide the location for Windows and macOS, and I’m guessing any system. 🙂

For example:

> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages

5. How can i temporarily disable a foreign key constraint in mysql?

Try DISABLE KEYS or

SET FOREIGN_KEY_CHECKS=0;

Make sure to

SET FOREIGN_KEY_CHECKS=1;

after.

6. How can i upgrade specific packages using pip and a requirements file?

I ran the following command and it upgraded from 1.2.3 to 1.4.0

pip install Django --upgrade

Shortcut for upgrade:

pip install Django -U

Note: if the package you are upgrading has any requirements this command will additionally upgrade all the requirements to the latest versions available. In recent versions of pip, you can prevent this behavior by specifying --upgrade-strategy only-if-needed. With that flag, dependencies will not be upgraded unless the installed versions of the dependent packages no longer satisfy the requirements of the upgraded package.

7. How to check django version?

Django 1.5 supports Python 2.6.5 and later.

If you’re under Linux and want to check the Python version you’re using, run python -V from the command line.

If you want to check the Django version, open a Python console and type

>>> import django
>>> django.VERSION
(2, 0, 0, 'final', 0)

8. 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 :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

9. What does on_delete do on django models?

This is the behaviour to adopt when the referenced object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. (1)

There are seven possible actions to take when such event occurs:

  • CASCADE: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE.
  • PROTECT: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT.
  • RESTRICT: (introduced in Django 3.1) Similar behavior as PROTECT that matches SQL’s RESTRICT more accurately. (See django documentation example)
  • SET_NULL: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL.
  • SET_DEFAULT: Set the default value. SQL equivalent: SET DEFAULT.
  • SET(...): Set a given value. This one is not part of the SQL standard and is entirely handled by Django.
  • DO_NOTHING: Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn’t exist). SQL equivalent: NO ACTION. (2)

Source: Django documentation

See also the documentation of PostgreSQL for instance.

In most cases, CASCADE is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. PROTECT and SET_NULL are often useful. Setting CASCADE where it should not, can potentially delete all of your database in cascade, by simply deleting a single user.


Additional note to clarify cascade direction

It’s funny to notice that the direction of the CASCADE action is not clear to many people. Actually, it’s funny to notice that only the CASCADE action is not clear. I understand the cascade behavior might be confusing, however you must think that it is the same direction as any other action. Thus, if you feel that CASCADE direction is not clear to you, it actually means that on_delete behavior is not clear to you.

In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let’s say you have an entry comment_A, which has a foreign key to an entry article_B. If you delete the entry comment_A, everything is fine. article_B used to live without comment_A and don’t bother if it’s deleted. However, if you delete article_B, then comment_A panics! It never lived without article_B and needs it, and it’s part of its attributes (article=article_B, but what is article_B???). This is where on_delete steps in, to determine how to resolve this integrity error, either by saying:

  • "No! Please! Don’t! I can’t live without you!" (which is said PROTECT or RESTRICT in Django/SQL)
  • "All right, if I’m not yours, then I’m nobody’s" (which is said SET_NULL)
  • "Good bye world, I can’t live without article_B" and commit suicide (this is the CASCADE behavior).
  • "It’s OK, I’ve got spare lover, and I’ll reference article_C from now" (SET_DEFAULT, or even SET(...)).
  • "I can’t face reality, and I’ll keep calling your name even if that’s the only thing left to me!" (DO_NOTHING)

I hope it makes cascade direction clearer. 🙂


Footnotes

(1) Django has its own implementation on top of SQL. And, as mentioned by @JoeMjr2 in the comments below, Django will not create the SQL constraints. If you want the constraints to be ensured by your database (for instance, if your database is used by another application, or if you hang in the database console from time to time), you might want to set the related constraints manually yourself. There is an open ticket to add support for database-level on delete constrains in Django.

(2) Actually, there is one case where DO_NOTHING can be useful: If you want to skip Django’s implementation and implement the constraint yourself at the database-level.

10. How to send a correct authorization header for basic authentication?

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn’t hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

Contact Us