This template contains a project, django_auth_template, and an app, api,
which are set up complete with user authentication and an example resource,
Mango, which has an example user ownership implementation.
- Download this template.
- Move the .zip file to your
sei/django-env/directory and Unzip it (creating a folder) -- NOTE: if the folder was already unzipped, use themvcommand line to move it to thesei/django-env/directory. - Empty
README.mdand fill with your own content. - Move into the new project and
git init. - Create and checkout to a new branch,
training, for your work. - Create a
.envfile - Add a key
ENVwith the valuedevelopmentexactly.- Note: When you deploy, you will create this key on Heroku the value
production. This will distinguish the development and production settings set in this template.
- Note: When you deploy, you will create this key on Heroku the value
- Run
pipenv shellto start up your virtual environment in thedjango-envfolder. - Run
pipenv install django-rest-auth django-cors-headers python-dotenv dj-database-urlin thedjango-envfolder.- Note: Any future Django projects you build in the
django-envfolder will have access to these packages.
- Note: Any future Django projects you build in the
- Create a psql database for your project
- Edit
settings.sqlthen runpsql -U postgres -f settings.sqlOR: - Run
createdb "project_db_name"OR: - Type
psqlto get into interactive shell. - Run
CREATE DATABASE "project_db_name";whereproject_db_nameis the name you want for your database.
- Edit
- Add the database name to the
.envfile using the keyDB_NAME_DEV. - Replace all instances of
django_auth_templatewith your application name. This includes the folder included in this repository. - Generate a secret key using this tool and add it to the
.envfile using the keySECRET. - Open the repository in VSCode with
code . - Make sure to read the Connecting Client section
for connecting with your
browser-templateorreact-auth-templatebased project.
After following the steps above, your .env file should look something like
the following, replacing project_db_name with your database name and
secret_key with your secret key.
ENV=development
DB_NAME_DEV=project_db_name
SECRET=secret_keyThis template includes a project django_auth_template which should be renamed
as part of the set-up steps. It includes the settings.py file with special
settings to be able to run both locally and on production. DO NOT ADD A NEW
OR MODIFY THE CURRENT DATABASES DEFINITION UNLESS INSTRUCTED TO DO SO.
There is also an app api which can be renamed if necessary. The api app
includes folders for models and view files, which can then be imported into
urls.py for use.
Commands are run with the syntax python3 manage.py <command>:
| command | action |
|---|---|
runserver |
Run the server |
makemigrations |
Generate migration files based on changes to models |
migrate |
Run migration files to migrate changes to db |
startapp |
Create a new app |
Before deploying, make sure you have renamed your project folder and replaced
all instances of django_auth_template with your app's name.
Once ready, you can follow the steps in the django-heroku-deployment-guide.
This template is intentionally minimal, and does not override many of Django's
defaults. This means connecting either the react-auth-template client to this backend involves updating that client code slightly.
Ultimately, Django and any other backend API framework should be able to build standalone backend APIs that can talk to any client. We just have to make sure the client is following some of the expectations that Django has by default.
When working on our "local" computer, we work on the localhost location. This
is paired with a port number to identify where our server is running on our
local machine. Our client templates use port 3000, for example, and run at
http://localhost:3000.
These templates also talk to a backend at a certain port, which is set to 8000
in the client templates. We might need to change the port in the URL the client
application uses when running locally.
In the browser-template this means modifying the config.js file, and in the
react-auth-template the apiConfig.js file.
This django template uses the port 8000 by default, so any client speaking to
this template's default server location would be http://localhost:8000.
Django defaults to expecting (and requiring) trailing forward slashes / on
requests. You'll need to make sure any requests you make from a client to this
template look something like http://localhost:8000/books/.
We've gotten used to the token syntax that the Express framework expects:
Bearer 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
However, the DRF TokenAuthentication class in this template is what defines
what our token syntax should look like when the client make an authenticated
request to our Django application.
When making authenticated requests from any client, make sure your tokens follow this pattern:
Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Our JavaScript conventions are to use camelCase when defining almost everything, however Python conventions (and therefore Django conventions) use
snake_case instead. We have to keep this in mind when sending data from a
client to a Django application.
Note: This section is only necessary if you are connecting this template to the
browser-templateand/or using the$.ajaxmethod.
When sending data with AJAX, we must stringify it with JSON.stringify. See the below example:
const create = function (data) {
return $.ajax({
url: config.apiUrl + '/mangos/',
method: 'POST',
headers: {
Authorization: 'Token ' + store.user.token
},
data: JSON.stringify(data)
})
}The request.data object becomes a QueryDict, and generally doesn't look the way we expect.
Instead of request.data, you must use request.body. We can then load the body as JSON with json.loads.
See the below (focusing on just the data) example:
# Import the `json` module
import json
....
class Mangos(APIView):
def post(self, request):
# Create variable to store readable JSON data
data = json.loads(request.body)
# pass the now Dictionary to the serializer, doing whatever you need
serializer = MySerializer(data=data['resource'])
.....pipenv shell moved me into a different directory!
Pipenv wants to be in the root directory, so if it thinks it's not then it will move you to what it thinks is the root of your repository. Exit out of the shell with
exit, then check if the folder it moved you to is a git repository. If you see a.gitfolder inside of thetrainingsfolder, for example, delete that folder so thattrainingsis no longer a "git repo." Then, you can change back into your project directory and try runningpipenv shellagain.
pipenv shell is complaining about my python version not matching
Our python version is defined in the
Pipfile. Simply replace the currentpython_version = "x.x"statement with the appropriate version.
SyntaxError pointing to manage.py when trying to run the server, migrate, etc.
Double-check your python version with
python --version. If you see a "2.x.x" version, then you need to use the commandpython3when running python scripts. You can also follow these guides to replace yourpythoncommand so it always uses python3.Mac: https://stackoverflow.com/questions/49704364/make-python3-as-my-default-python-on-mac/49711594
Linux: https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux
Error: No module named when trying to run the server
If Python can't find the module that is your project name, then very likely you forgot a very important piece of the preparation steps. You need to make sure you rename the project folder as well.
I made changes to my models & ran my migrations but it says "No migrations to apply"
Double-check that you generated the migration files before you tried to run them. This means running
makemigrationsbeforemigrate.
Errors with psycopg2
There's a lot to read about this issue if you want: psycopg/psycopg2#674 https://www.psycopg.org/articles/2018/02/08/psycopg-274-released/
This template uses
psycopg2-binaryto minimize errors during project development. If you have errors withpsycopg2anyway, notify an instructor.
- All content is licensed under a CCBYNCSA 4.0 license.
- All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.