Django is a wonderful Python web framework, and its command line utility is indispensable when developing Django sites. However, the command to start new projects is a bit tricky. The official tutorial shows the basic case – how to start a new project from scratch using the command:
$ django-admin startproject [projectname]
This command will create a new directory using the given project name and generate the basic Django files within it. However, project names have strict rules: they may contain only letters, numbers, and underscores. So, the following project name would fail:
$ django-admin startproject my-new-django-project CommandError: 'my-new-django-project' is not a valid project name. Please make sure the name is a valid identifier.
Another problem is initializing a new Django project inside an existing directory:
$ mkdir myproject $ django-admin startproject myproject CommandError: '/path/to/myproject' already exists
These two problems commonly happen when using Git (or other source control systems). The repository may already exist, and its name may have illegal project name characters. The project could be created as a sub-directory within the repository root, but this is not ideal.
Thankfully, there’s a simple solution. The “django-admin startproject” command takes an optional argument after the project name for the project path. This argument sidesteps both problems. The project root directory and the Django project file directory can have different names. The example below shows how to change into the desired root directory and start the project from within it using “.”:
$ cd my-django-git $ django-admin startproject myproject . $ ls manage.py myproject
This can be a stumbling block because it is not documented in Django’s official tutorial. The “django-admin help startproject” command does document the optional directory argument but does not explain when this option is useful. Hopefully, this article makes its use case more intuitive!