Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Kickstart Coding's Django Project Starter Template

License

NotificationsYou must be signed in to change notification settings

kickstartcoding/django-kcproject-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Kickstart Coding Logo

Kickstart Coding: Django Project Starter

This is an example start project forKickstart CodingDjango projects.

It provides a solid foundation for building a Django project that's ready tolaunch to Heroku or similar web-hosting service.

About

Features

  • Clean, simple, and up-to-date: Only a few changes from the officiadjango-admin startproject

  • Bootstrap 5: It's all set-up with Bootstrap 5.0.2 CSS, a few example pages,anddjango-bootstrap5 for easily bootstrap-based forms

  • Accounts:

    • Log-in and sign-up pages
    • Custom user class
    • User profile page and user editing page
  • Heroku support: It's onegit push away from publishing to the world

  • Pipenv: It's set-up to use Pipfile

  • Code standards: This was created to be a happy medium between the defaultdjango-admin starting template and heavier weight scaffolding such asAudrey / Daniel Greenfield'sDjango Cookiecutter,which might be better for larger projects

  • Easy development:

    • Separatelocal andproduction settings
    • Use Sqlite locally and postgres in production
    • While for bigger projects production / dev parity is vitally important,this is great for getting started with smaller projects
  • Misc nice stuff:

    • django-debug-toolbar -- great debugging tool
    • Error pages

Who is this for

  • This is fornew Python/Django programmers, includingcoding classstudents who want a solid start for a Django project that uses SQLite whendeveloping locally, and is ready to deploy Heroku provisioned Postgresdatabase.

  • The documentation assumes you already have fundamental Python, Django, Bashand Heroku knowledge. If you are new to Heroku, read ourHeroku GettingStarted guide.If you are new to Postgres, read ourPostgres Getting Started guide.

  • The documentationdoes not explicitly support Windows. It assumes you useeithermacOS or aGNU/Linux distribution such as Ubuntu. That said,it might work.

This was originally created for Kickstart Coding, the cutting-edge,personalized, and affordable "custom-paced" full-stack online coding program.Learn more and enroll in our Python / Django, JavaScript / React webdevelopment, and career development courseshere.

Development

  • Prereqs:1) You have Pipenvinstalled. 2) Youhave Django admin installed globally (macOS typepip3 install django,Ubuntu GNU/Linux, typesudo pip3 install django)

Running locally

  1. Assumingmycoolproject is the name of your project, you should start a newproject using this template as follows:
django-admin startproject --template=https://github.com/kickstartcoding/django-kcproject-starter/archive/master.zip mycoolproject
  1. Go into the newly created project, and usepipenv to get your virtualenvsetup:
cd mycoolprojectpipenv shellpipenv install --skip-lock --dev

Note: It's probably okay if you get errors while installingpsycopg2and/orgunicorn, such as'ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.'. Thesepackages are not needed for development. That's why we have--skip-lockspecified to prevent these errors from stopping the installation.

  1. This starter projectdoes not include migrations. Make migrations as such:
python manage.py makemigrations accounts
  1. Run the migrations to actually create the SQLite database:
python manage.py migrate
  1. Get the server running:
python manage.py runserver

Setting up with GitHub repo

  1. Create a new repo on GitHub, andBE SURE TO NOT check "initialize withREADME.md" or.gitignore or anything. You want to make atruly blank repofor these steps to work without a hiccup. Just fill in the name anddescription, and nothing else.

  2. Now, initialize and push the code we have by running this in thecommand-line:

ls# Ensure you are "next to" the manage.py, etcgit init# Initalize thisgit add -A# Add all your filesgit commit -m"first"# Make a commit
  1. Finally, link up your local repository with the git one, and push. Followthe instructions provided on the github.com page. They will look a little likethis, except instead ofjaneqhacker/mycoolproject it will be whatever yourusername is and your repo name is:
git remote add origin git@github.com:janeqhacker/mycoolproject.gitgit push -u origin master

File structure

Directory structure description below:

[name_of_project]/-config/-base.py# Stores most settings-local.py# Stores settings only for local dev-production.py# Stores settings only used by production (e.g. Heroku)-urls.py# Global urls.py, in turn includes urls.py in apps-apps/# A directory to store all our custom apps-accounts/# An example custom app that includes sign-up and log-in-models.py# Customized user class is here-urls.py# URLs for sign-up and log-in pages-views.py# Views for sign-up and log-in pages-forms.py# Form for editing user profile, sign-up-templates/# Templates for user profile stuff-core/# An example custom app that has some static pages-static/# Static files-templates/# Core templates, including base templates-etc-manage.py# Entry point-Pipfile# Development requirements

Production

Provisioning on Heroku

  1. Creating a new Heroku app & Postgres Database (only need to do this once perHeroku):
heroku create# Create a Heroku app (only run this if you haven't already)heroku addons:create heroku-postgresql:hobby-dev
  1. Optional: Confirm that the database is working by connecting to it with thecommand-line client (Ctrl+D to exit):
heroku pg:psql
  1. Push to Heroku
git push heroku master
  1. Run the migrations on the remote Postgres database. That can be done asfollows:
heroku run python manage.py migrate
  1. Your site should work! View it in your browser.

  2. You'll also want to add aSECRET_KEY to Heroku to make your site secure:

heroku config:set SECRET_KEY=randomly hit keys

NOTE: Where it says "randomly hit keys", do just that! Just type a really longrandom series of letters and numbers. You'll never have to remember it again.


Troubleshooting

Issue:django-admin startproject fails

If you get an error like this while trying to do the initialstartproject:

CommandError: couldn't download URL https://github.com/kickstartcoding/django-kcproject-starter/archive/master.zip to master.zip<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>

Work around

  1. Go tohttps://github.com/kickstartcoding/django-kcproject-starter

  2. Click the button[Clone or download v], then click[Download Zip]

  3. Save thedjango-kcproject-starter-master.zip file somewhere, such as inyour~/Downloads directory, or in the directory you are working

  4. Now, run the same command as before (again usingmycoolproject as theexample name), except referencing the downloaded copy. Example commands below:

#  If you saved it in ~/Downloads, then do:django-admin startproject --template=~/Downloads/django-kcproject-starter-master.zip mycoolproject#  If you saved it in the current directory:django-admin startproject --template=./django-kcproject-starter-master.zip mycoolproject

Solution

This can happen to some users, often on macOS, and has to do with SSLcertificates and/or Python3 having some installation issues. To properly solvethis issue, you may need to upgrade your Python3 installation, and/or addupdated certificates. This can be tricky and OS-specific, so consider using thework-around above.

Issue:pipenv install --dev fails onpsycopg2 and/orgunicorn

You might get large error messages while installing these packages. It mightlook like:

    'ERROR: Command errored out with exit status 1: python setup.py egg_info    Check the logs for full command output.'

Work around

Ignore it, and keep on developing!

These packages are not needed for development. Likely everything else will workfine, and you won't run into any issues while developing, since the localdevelopment set-up is using Sqlite, not Postgres, and the local developmentserver doesn't usegunicorn.

Solution

For GNU/Linux based systems,psycopg2 this can often be properly solved bysimply installing the Postgres client locally on your operating system (e.g.sudo apt install postgres). For Macintosh-based operating systems, thesolution might be more involved, and we'd recommend searching for Mac-specificanswers about Python3psycopg2 failing to compile.

Issue:collectstatic while deploying to Heroku fails

If you get an error like this:

    remote:            conn.setdefault('ATOMIC_REQUESTS', False)    remote:        AttributeError: 'NoneType' object has no attribute 'setdefault'

That might mean your Postgres database isn't yet created, and that you possiblyskipped that step:

    heroku addons:create heroku-postgresql:hobby-dev

Going further

Mailgun

  1. Add env variables to Heroku as such:
heroku config:set MAILGUN_API_KEY=(YOUR API KEY AS SPECIFIED BY MAILGUN)heroku config:set MAILGUN_DOMAIN=(YOUR DOMAIN AS SPECFIEID BY MAILGUN)
  1. Install anymail
pipenv install django-anymail
  1. Then, add the following to yourproduction.py:

     # Anymail (Mailgun) # ------------------------------------------------------------------------------ # https://anymail.readthedocs.io/en/stable/installation/#installing-anymail INSTALLED_APPS += ['anymail'] EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' # https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference ANYMAIL = {     'MAILGUN_API_KEY': os.environ.get('MAILGUN_API_KEY'),     'MAILGUN_SENDER_DOMAIN': os.environ.get('MAILGUN_DOMAIN') }

AWS S3

If you want to be able to upload files and not have them be wiped out each timeyou launch, you'll need to set up Amazon S3 or an equivalent competing ObjectStore (such as Digital Ocean's Object Store).

Setup AWS and get your keys by following this guide:

https://devcenter.heroku.com/articles/s3

Integrating with React (Create React App)

  • This assumes familiarity with React and Create React App (CRA).
  • These instructions will work with other frontend frameworks as well thatfollow a similar development pattern as CRA, with only a few tweaks necessarybased on the commands they expect and the files and directories theirbuild-tools generate
  1. Start a new React app called "frontend", by running the following command inthe same directory asmanage.py:
npx create-react-app frontend
  1. Build the frontend. The goal here is to just have the "sample app" thatcomes with CRA built and residing in thebuild/ directory:
cd frontendnpm run build
  1. Configure Django to serve up React's compiled JS, CSS, etc as additionalstatic files. Put this at the end of your "base.py" settings file:
STATICFILES_DIRS = [    os.path.join(BASE_DIR, '..', 'frontend', 'build', 'static'),]
  1. Create a view-function in Django to serve up the frontend's "index.html" inthe build directory to "kick things off". Open upapps/core/views.py and addthe following code:
fromdjango.httpimportHttpResponsedefreact_app(request):index_contents=open('./frontend/build/index.html').read()returnHttpResponse(index_contents)
  1. Create a URL route for your new view-function. Open upapps/core/urls.pyand add the following URL path to the end of the list, before the]:
path('app/', views.react_app),
  1. Now, run the Django server as you normally would, and navigate tolocalhost:8000/app/ -- if you did everything correctly, you should see theCRA sample application in your browser!

  2. If you are using React Router, you will want Django to serve up React inlieu of a 404 page, to permit ANY route to go to React Router (not justapp/or the one you specify). Go into the project-level urls.py, and add thefollowing to the very end of the file:

from django.urls import re_pathfrom app.core import viewsurlpatterns += [re_path(r'.*', views.react_app)]

Tips:

  • To keep on using CRA's test server during development so you getlive-reloading, running both Django and node simultaneously. To do this,you'll have to configure CRA's proxy setting, by editingfrontend/package.json to include"proxy": "http://localhost:8000/",
  • After changes to your front-end, be sure to runnpm run build to regeneratethe compiled version of your JS.
  • When deploying to production, make sure that thebuild/ directory getsincluded in Git (remove it from .gitignore in the root directory and thefrontend/ directory if it happens to be in either)

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp