Skip to content

Instantly share code, notes, and snippets.

@roostercrab
Created October 10, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roostercrab/8ba69b19e2b42f0301b16842ed384fd7 to your computer and use it in GitHub Desktop.
Save roostercrab/8ba69b19e2b42f0301b16842ed384fd7 to your computer and use it in GitHub Desktop.
Django gist
POSTGRES EXPORT/IMPORT:
SELECT * FROM "ScheduledClass";
COPY "ScheduledClass" TO '/Users/jesseshea/Desktop/scheduled_class.csv' DELIMITER ',' CSV HEADER;
COPY "ScheduledClass" FROM '/Users/jesseshea/Desktop/scheduled_class.csv' DELIMITERS ',' CSV HEADER;
REPLACE MULTIPLE FIND REPLACE EXCEL:
Sub MultiFindNReplace()
'Update 20140722
Dim Rng As Range
Dim InputRng As Range, ReplaceRng As Range
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Original Range ", xTitleId, InputRng.Address, Type:=8)
Set ReplaceRng = Application.InputBox("Replace Range :", xTitleId, Type:=8)
Application.ScreenUpdating = False
For Each Rng In ReplaceRng.Columns(1).Cells
InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value, Lookat:=xlWhole
Next
Application.ScreenUpdating = True
End Sub
[~/Desktop/Development]virtualenv crescent_django_vuejs
[~/Desktop/Development]cd crescent_django_vuejs && source bin activate
(crescent_django_vuejs) [~/Desktop/Development/crescent_django_vuejs]
(crescent_django_vuejs) [~/Desktop/Development/crescent_django_vuejs]pip install django
MAKE SIMPLE VENV:
python3 -m venv env
source env/bin/activate
FOR PYENV:
mkdir *myproject*
cd *myproject*
pyenv virtualenv 3.6.8 *myproject*
pyenv local *myproject*
pyenv activate *myproject*
pip install pipenv
python --version
pyenv version
GET RANDOM KEY:
from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
CHECK FOR COMMON PROBLEMS:
django-admin check
DEBUG:
setting in manage.py to change the amount of output:
--verbosity
assert False, value
put into views to stop operation and deliver trace
{% load debug_tags %}
{% set_trace %}
{% variables %}
{% attributes *varname* %}
{% details *varname* %}
template debugger
CREATE A BLOCK TO SEE WHAT IS BEING PASSED:
{% block assignment_questions %}
{{ assignment_questions }}
{% endblock assignment_questions %}
CHECK DJANGO VERSION
python -c "import django; print(django.get_version())"
HOW TO HEROKU WITH DJANGO:
brew install pyenv
#next two lines needed for pyenv on Mojave
xcode-select --install
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
pyenv install 3.6.8
git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile
exec "$SHELL"
brew install pyenv-virtualenv
pip install --upgrade pip
pip install django
python -m django --version
django-admin startproject mysite
curl https://cli-assets.heroku.com/install.sh | sh
*myproject*/mysite/
git init
heroku create
pip install gunicorn
cd *myproject*/mysite/
echo 'web: gunicorn mysite.wsgi --log-file -' > Procfile
pip install django-heroku
vi *myproject*/mysite/mysite/settings.py
#TOP:
import django_heroku
...
# All of your settings here
...
#BOTTOM:
django_heroku.settings(locals())
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
Reverse all of your heroku application migrations:
heroku run python manage.py migrate *appname* zero
*myproject*/mysite
pip freeze > requirements.txt
echo 'python-3.6.8' > runtime.txt
touch .gitignore
vi .gitignore
### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
git add .
git commit -am "Initialize Django project"
install all files with:
pipenv install *thing*
pipenv lock --pre --clear
pipenv lock
pipenv update
git push heroku master
TEST ON HEROKU
GET DATABASE WORKING:
heroku config
pip install python-dotenv
pip freeze > requirements.txt
for Heroku just:
pipenv lock
python manage.py runserver_plus
#can step through the code???
echo 'DATABASE_URL=sqlite:///db.sqlite3' > .env
echo '.env' >> .gitignore
BAKE APPS BY CREATING ALL VIEWS AUTOMAGICALLY:
pip install django-baker
python manage.py bake *app1* *app2*
OR
python manage.py bake *app1* *app2*:*model*,*other_model*
IN MAIN URLCONF:
(r'^*app1*/', include('*app1*.urls')),
BUT NOT WITH REGEX
vi *myproject*/mysite/mysite/settings.py
import dj_database_url
import dotenv
# This line should already exist in your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# This is new:
dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
dotenv.load_dotenv(dotenv_file)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
DATABASES = {}
DATABASES['default'] = dj_database_url.config(conn_max_age=600)
...
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# This should already be in your settings.py
django_heroku.settings(locals())
# This is new
del DATABASES['default']['OPTIONS']['sslmode']
python manage.py migrate
python manage.py createsuperuser
git add .
git commit -am "Implement database connection"
git push heroku master
heroku run python manage.py createsuperuser
heroku run bash
heroku pg:psql
If it gets messy, KILL IT WITH FIRE:
heroku pg:reset
heroku run ./manage.py migrate -r *heroku instance*
git remote rename heroku heroku-app-one
LIST ALL YOUR GIT REMOTES NAMES
git remote -v
git push staging master
git push production master
git config heroku.remote staging
# in Heroku’s shell you should only ever have to migrate and never makemigrations.
heroku run python manage.py migrate
heroku run python manage.py migrate -r development
heroku run python manage.py migrate -r staging
heroku run python manage.py migrate -r production
WAY TO BACKUP AND THEN RESTORE POSTGRES DB FOR HEROKU
heroku pg:backups:capture -r development
heroku pg:backups:download -r development
heroku pg:reset -r development
heroku run python manage.py migrate -r development
*** need to get credentials from heroku db ***
pg_restore --verbose --clean --no-acl --no-owner -h *remote_host* -U *user_name* -d *database_name* latest.dump
pg_restore --verbose --clean --no-acl --no-owner -h ec2-75-101-147-226.compute-1.amazonaws.com -U ogngdkxaqnvchd -d d9amu884crl0dt latest.dump
revert all migrations
./manage.py migrate *my_app* zero
how to get into sqlite3 cmd line
sqlite3 db.sqlite3
.tables
Delete all data from table:
DELETE
FROM
*whatever_table_you_want_gone*;
CLEAR THE DATABASE WITHOUT CHANGING MIGRATIONS:
django-admin flush
SQUASH MIGRATIONS INTO AS FEW FILES AS POSSIBLE:
django-admin squashmigrations app_label [start_migration_name] migration_name
# Create a dot file
$ ./manage.py graph_models -a > my_project.dot
cmd-shift-P:
graphviz show preview
to do cmd line stuff:
./manage.py shell
**pip install django
pip install "cookiecutter>=1.4.0"
cookiecutter https://github.com/pydanny/cookiecutter-django
mkdir ~/venvs
virtualenv ~/venvs/*VENV_NAME*
source ~/venvs/*VENV_NAME*/bin/activate
./manage.py runserver
cd projects
mkdir myhellowebapp
cd myhellowebapp
virtualenv venv
source venv/bin/activate
pip3 install virtualenvwrapper
source virtualenvwrapper.sh
mkvirtualenv *name*
deactivate
workon *name*
pip install -r requirements.txt
pipenv install django==2.1.5
pip install django-taggit
pip install django-registration-redux
pipenv shell
pip install -r requirements.txt
or
https://github.com/wsvincent/djangox
ficjnvvvkirfblcrhgttj
django-admin
django-admin startproject education-laser .
django-admin startapp *new-app*
python manage.py runserver
python manage.py migrate
pip freeze > requirements.txt
grading/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse('<h1>grading Home</h1>')
create = grading/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='grading-home'),
]
gitk
view the tree of commits
accelegraded/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('grading/', include('gradings.urls')),
]
create = templates directory in grading folder
create = grading folder in templates directory
There will be an app created already in:
grading/apps.py
take the name:
GradingConfig
and paste it into:
accelegraded/settings.py
add:
INSTALLED_APPS = [
'grading.apps.GradingConfig',
etc..
in grading/views.py:
def home(request):
return render(request, 'grading/home.html')
command-shift-r resets css and hard reloads webpage
python manage.py makemigrations
gets migrations ready
python manage.py migrate
does migrations
python manage.py createsuperuser
makes the admin account
database class options:
last_modified = = models.DateTimeField(auto_now=True)
#always current date, good for last modified
when_created = models.DateTimeField(auto_now_add=True)
#sets date posted when created, won't ever update
date_posted = models.DateTimeField(default=timezone.now)
python manage.py sql migrate grading 0001
shows what sql commands will be used
python manage.py shell
opens shell
from grading.models import Questions
from django.contrib.auth.models import User
User.objects.all()
User.objects.first()
User.objects.last()
User.objects.filter(username='testuser') <-- gives queryset
User.objects.filter(username='testuser').first()
put in variable:
user = User.objects.filter(username='jesse').first()
Make user login:
python manage.py startapp users
from django.contrib import messages
messages.debug
messages.info
messages.success
messages.warning
messages.error
Change db file to django model:
python manage.py inspectdb
URL -> View -> Model (typically) -> Template
class_name_queryset = Class.objects.filter(pk=class_id).values('class_name')
class_name_queryset = Class.objects.filter(pk=class_id).values_list('class_name')
How to put all fields in form:
in CreateView:
form_class = AssignmentForm
Output database data:
https://coderwall.com/p/mvsoyg/django-dumpdata-and-loaddata
./manage.py dumpdata > db.json
./manage.py dumpdata admin > admin.json
dumpdata for backup specific table:
dump only the content in "django admin.logentry" table
./manage.py dumpdata admin.logentry > logentry.json
dump the content in django auth.user table
./manage.py dumpdata auth.user > user.json
if going to a different database exclude data specific to other one:
./manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
***should probably exclude content types no matter what, even if destroying and rebuilding db
Load database data:
./manage.py loaddata db.json
./manage.py loaddata admin.json
./manage.py loaddata user.json
./manage.py loaddata etc...
******************* HOW IT WORKS *******************
first create a view
views.py:
def home(request):
return render(request, 'grading/home.html')
then create a path to the view
grading/urls.py:
urlpatterns = [
path('', views.home, name='grading-home'),
]
then create a link to that url file in the main app url folder
accelegraded/urls.py:
urlpatterns = [
path('grading/', include('grading.urls')),
]
Create an html file in grading/templates/grading
home.html:
<h1>Grading Home</h1>
from apps.py take the name GradingConfig and paste it into accelegraded/settings.py
INSTALLED_APPS = [
'grading.apps.GradingConfig',
]
ENUM
from django.db import models
from enum import Enum
class IceCreamOrder(models.Model):
class FLAVORS(Enum):
chocolate = ('ch', 'Chocolate')
vanilla = ('vn', 'Vanilla')
strawberry = ('st', 'Strawberry')
chunky_munky = ('cm', 'Chunky Munky')
@classmethod
def get_value(cls, member):
return cls[member].value[0]
flavor = models.CharField(
max_length=2,
choices=[x.value for x in FLAVORS]
)
CHOICE MODEL
# orders/models.py
from django.db import models
class IceCreamOrder(models.Model):
FLAVOR_CHOCOLATE = 'ch'
FLAVOR_VANILLA = 'vn'
FLAVOR_STRAWBERRY = 'st'
FLAVOR_CHUNKY_MUNKY = 'cm'
FLAVOR_CHOICES = (
(FLAVOR_CHOCOLATE, 'Chocolate'),
(FLAVOR_VANILLA, 'Vanilla'),
(FLAVOR_STRAWBERRY, 'Strawberry'),
(FLAVOR_CHUNKY_MUNKY, 'Chunky Munky')
)
flavor = models.CharField(
max_length=2,
choices=FLAVOR_CHOICES
)
CAN DO:
>>> from orders.models import IceCreamOrder
>>> IceCreamOrder.objects.filter(flavor=IceCreamOrder.FLAVOR_CHOCOLATE)
[<icecreamorder: 35>, <icecreamorder: 42>, <icecreamorder: 49>]
MODELS NULL BLANK?
We’ve put this guide together to serve as a guide for standard usage of these model field arguments.
Field Type Setting null=True Setting blank=True
CharField, TextField,
SlugField,
EmailField,
CommaSeparated-
IntegerField,
UUIDField
Okay if you also have set both
unique=True and blank=True.
In this situation, null=True is
required to avoid unique
constraint violations when saving
multiple objects with blank
values.
Okay if you want the
corresponding form widget
to accept empty values. If
you set this, empty values
are stored as NULL in the
database if null=True and
unique=True are also set.
Otherwise, they get stored
as empty strings.
FileField,
ImageField
Don’t do this.
Django stores the path from
MEDIA_ROOT to the file or to the
image in a CharField, so the same
pattern applies to FileFields.
Okay.
The same pattern for
CharField applies here.
Field Type Setting null=True Setting blank=True
BooleanField Don’t do this. Use
NullBooleanField instead.
Don’t do this.
IntegerField,
FloatField,
DecimalField,
Field Type Setting null=True Setting blank=True
DatetimeRangeField
and DateRangeField
Okay if you want to be able to set
the value to NULL in the database.
Okay if you want the
corresponding form widget
to accept empty values, or if
you are using auto_now or
auto_now_add. If so, you
will also want to set
null=True.
JSONField Okay. Okay.
OBJECT DOES NOT EXIST
from django.core.exceptions import ObjectDoesNotExist
from flavors.models import Flavor
from store.exceptions import OutOfStock
def list_flavor_line_item(sku):
try:
return Flavor.objects.get(sku=sku, quantity__gt=0)
except Flavor.DoesNotExist:
msg = 'We are out of {0}'.format(sku)
raise OutOfStock(msg)
def list_any_line_item(model, sku):
try:
return model.objects.get(sku=sku, quantity__gt=0)
except ObjectDoesNotExist:
msg = 'We are out of {0}'.
GOOD QUERIES
from django.db.models import F
from models.customers import Customer
customers = Customer.objects.filter(scoops_ordered__gt=F('store_visits'))
IS DOING THIS IN SQL:
SELECT * from customers_customer where scoops_ordered > store_visits
WRAP HTTP IN TRANSACTION
# settings/base.py
DATABASES = {
'default': {
# ...
'ATOMIC_REQUESTS': True,
},
}
Example 20.2: Using settings.AUTH_USER_MODEL to Define Model Relations
from django.conf import settings
from django.db import models
class IceCreamStore(models.Model):
owner = models.OneToOneField(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=255)
Model.objects.all()
Model.objects.get()
Model.objects.filter(*column*__startswith='X')
Courses.objects.filter(name__startswith='X').filter(students__username__startswith='L')
#for querying join tables
qs.filter(students__username__startswith='r')
searches across multiple tables, used for join tables?
# def post(self, request, *args, **kwargs):
# self.object = StudentScheduledClass(scheduled_class=kwargs['scheduled_class'])
# return super().post(request, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment