Django Flashcards
heroku: To open your app in the browser, type
heroku open
django: To import HttpResponse, type
from django.http import HttpResponse
django: Inside of urls.py you need to import
from . import views
or from .views import *
django: By convention, model names should be
singular
django: App names are usually
the plural of the main model your app will be about.
django: To create database entries from the django shell, type
from app_name.models import Modelname
django: To access the database from within views.py, type
from .models import Model
from .models import *
django: To create a urls.py
from django.urls import path, include
urlpatterns = [
path(‘url’, views.view_name, name=”string”),
]
django: To create templates for an app, you need to first
create a templates folder inside the app and another folder inside the templates folder with the same name as the app.
django: To create templates for an app, you need to first
create a templates folder inside the app.
django: To render a template from a view function, type
return render(request, “app_name/template.html”, {“pass_in_var”: local_var})
django: To tell django where to look for static files
go to settings.py and type
STATICFILES_DIRS = (
os.path.join(BASE_DIR, “assets”),
)
note: must have trailing comma
django: To specify a one to many relationship in a model, type
other_model = models.ForeignKey(OtherModel)
django: When you create a new model and want to include it in the admin area, you must
include it in this apps admin.py file.
from .models import Modelname
admin.site.register(Modelname)
django: To install django, type
pip install django
django: The stub is
the app-like folder automatically created django that holds site wide files.
Html: the form tags must have the two attributes
The type of http method to use (post or get)
The url to send the data to.
django: The python manage.py makemigrations command makes migrations for all of the
installed apps in settings.py
django: In the django shell, before you can add new instances you need to import the model by typing
from app_name.models import Modelname
django: When creating new models, it is usefull to add the __str__ method so that
Modelname.objects.all() returns the names of the objects rather than saying “Modelname Object” if you ever need to iterate through them for a view.
django: When adding new urls to a urls.py file, remember to start it with
url(
django: urls that are assigned in an apps urls.py are
appended to the to the url assigned in the stubs site wide urls.py
django: pk stands for
primary key (it is the id of the record that is automatically generated by django)
django: when creating an html template, model.step_set.all does not require
brackets
django: when creating an html template, to loop through models related records from it’s foreign key, type
{% for item in model.step_set.all %}
item.name
{% endfor %}
django: To make the return of Modelname.objects.all() come out in a specific order, you must add the following to the model:
class Meta() ordering = ["my_attribute",]
Note: more ordering columns can be added to the list.
Errors on the server should always generate the error page numbered
500
django: To throw a 404 when a bad url is used, type
into views.py
from django.shortcuts import get_object_or_404
def Modelname(request, pk): my_attribute = get_object_or_404(Modelname, pk=pk) return render...
django: So the parameters are captured properly, you must order the urls in urls.py from
most parameters to least.
django: To give a url a name and set the namespace, type
in the app:
url(r’^$’, views.hello_world, name=”my_url”),
and in the stubs site wide urls.py:
url(r’^page/’, include(“app_name.urls”, namespace=”app_name”)),
django: To reference a url based on its set name from inside an html template, type
namespace:url_name
re: To make a character optional, type
? after it
django: django forms do not automatically render the
form tags. Only the input tags.
django: To create a view that passes a form to the template from forms.py and then expects the post request from it, and if it receives a valid one, returns “Thanks”, type
from .forms import Myform
def form_view(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): ... return HttpResponse("Thanks!") else: form = MyForm() return render(request, "app_name/template.html", {"form": form})
django: To create a django form or model form in a template, type
-form action="/page/" method="post"> {% csrf_token %} {{ form }} -input type="submit" value="Submit" /> -/form>
django: To create a form that does not interact with the database, type
in forms.py
from django import forms
class MyForm(forms.Form): name = forms.CharField(label='Name', max_length=100)
django: columns that are auto generated (like created at) should not
be added as a field to a ModelForm
django: To create a ModelForm that saves to the database, type
forms.py
from django import forms
from .models import Modelname
class MyModelForm(forms.ModelForm): class Meta: model = Modelname fields = ["column1", "column2"]
views.py
from .forms import MyModelForm
def view_name(request): if request.method == "POST": form = MyModelForm(request.POST) if form.is_valid(): form.save() return HttpResponse("Thanks!") else: form = MyModelForm() return render(request, "app_name/template.html", {"form": form})
django: When you need a form with some fields that save to separate other models, you need to
create both forms and include them in the views form tags together. Then validate both of them before saving.
django: The user model is
automatically created.
django: To import the User model, type
from django.contrib.auth.models import User
django: When inheriting from the UserCreationForm, it is prohibited to not
supply fields in the meta class
django: To create a user registration form with username, email, and password confirmation, type
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserForm(UserCreationForm): class Meta: model = User fields = ["username", "email"]
django: To create a view that checks if there is a post request of a UserForm, and then saves that UserForm and then logs the user in immediately after saving, type
from django.contrib.auth import authenticate, login
from .forms import UserForm
def my_view(request):
if request.method == “POST”:
form = UserForm(request.POST)
if form.is_valid():
form.save()
user = authenticate(username=request.POST[‘username’], password=request.POST[‘password’])
login(request, user)
return HttpResponse(“Thanks!”)
else:
form = UserForm()
return render(request, “app_name/template.html”, {“form”: form})
django: To make a view check whether or not a user is authenticated/logged in, type
if request.user.is_authenticated():
return …
if not request.user.is_authenticated():
return …
django: The templates for the django.contrib.auth.views must be
created manually.
django: the logout url from the django.contrib.auth.views, by default, looks for the template in
templates/registration/logged_out.html
django: the login url from the django.contrib.auth.views, by default, looks for the template in
templates/registration/login.html
django: all of the django.contrib.auth.views pass a variable to the template called
form
django: the password_change url from the django.contrib.auth.views, by default, looks for the template in
templates/registration/password_change_form.html
django: When using the django.contrib.auth.views login url, if the login is successful, and there is no “next” variable, it redirects to
settings.LOGIN_REDIRECT_URL
and if that is not set, then accounts/profile
django: To use all of the django.contrib.auth.urls urls, type
from django.conf.urls import include, url
urlpatterns = [
url(r’^’, include(‘django.contrib.auth.urls’))
]
django: To add extra columns to the default User model, type
from django.contrib.auth.models import User
class Modelname(models.Model): user = models.OneToOneField(User) column1 = models.CharField(max_length=100)
django: when using the include() function inside of url() remember to
put quotes around the path to the app urls.
django: The sequence of steps you must take to create a new app is
django-admin startproject project_name python manage.py migrate python manage.py createsuperuser python manage.py startapp app_name install the app git init add xx to .gitignore create a templates folder in app create account and app_name folders in templates create hello_world_template.html in templates (extends and content blocks) create parallel base.html with default content create static/app_name/styles.css in app_name add .move-down {margin-top: 50px;} to the body div container python manage.py runserver create a model create a view create a url create the site wide url in the stub register the models in the admin make migrations migrate
django: It is not HttpRequest(), it is
HttpResponse()
django: The action for the form in the login.html template should be
-form method=”post” action=”{% url ‘django.contrib.auth.views.login’ %}”>
django: When importing styles.css make the href path by typing
{% load staticfiles %}
-link rel=”stylesheet” href=”{% static “app_name/styles.css” %}”>
Note: Do not start path with slash
django: The path for static files should be
project_name/app_name/static/app_name/styles.css
django: in order to set the form action to action=”{% url “url_name” %}” you must fist
add name=”url_name” to the url in urls.py
django: To return the key value if your url is www.example.com/?key=value, type
request.GET.get(“key”, “”)
django: To include the custom stylesheet in django, type
{% load staticfiles %}
-link rel=”stylesheet” href=”{% static “app_name/styles.css” %}”>
django: The fields you specify in your UserCreationForm must
exactly match the input names in your templates form.
django: To set one django.contrib.auth view to have a custom template name, type
urlpatterns = [
url(r’^login’, django.contrib.auth.views.login, {‘template_name’: ‘login_template.html’} ),
]
django: you must place base.html in
the templates folder, not with all the other html files.
a virtualenv is
a package on the same server that is separate from the main one so you can use two versions of django together.
django: To add a class to a form field in a model form, type
class MyModelForm(models.ModelForm): class Meta: model = Modelname widgets = { 'my_field': TextInput(attrs={"class": "myclass"}), }
django: If you are overriding django’s default form but still using the forms {{ csrf_token }} then you might need to add to the view
from django.middleware.csrf import get_token
def user_creation_view(request):
if request.method == “POST”:
form = UserForm(request.POST)
get_token(request)
django: The mandatory parameter for models.CharField() is
max_length=100
django: To create an if statement in a template that displays the username if logged in or says “Log in”, type
{% if user.is_authenticated %} Hey, {{ request.user.username }} {% else %} Log In {% endif %}
pythonanywhere allows you to
schedule scripts
django: To exclude a field from the generated form in forms.py, type
class Meta: model = Modelname exclude = ['field1']
django: Remember 3 things
always put a comma at the end of urls, and always write a == in if request.method == “POST”:, migrate after model changes
django: To wipe all data from the database, type
python manage.py flush
django: An alternative to saving a form in order to create a new user is
username = request.POST.get('username', None) password = request.POST.get('password', None) user = User.objects.create_user(username=username, password=password)
django: To recieve a post request with a user registration and a couple UserProfile fields and create the relationship between them, type
def user_creation_view(request): if request.method == "POST": username = request.POST.get('username', None) password = request.POST.get('password', None) user = User.objects.create_user(username=username, password=password) user.save() user = authenticate(username=username, password=password) login(request, user) interests = request.POST.get('interests', None) age = request.POST.get('age', None) pk = request.user user_profile = UserProfile.objects.create(age=age, interests=interests, user=pk) return render(request, "profiles/user_creation_template.html")
django: To create a view that passes in an object for the User that is currently authenticated, type
def user_profile_view(request): query_set = UserProfile.objects.get(user = request.user.id) return render(request, "profiles/user_profile_template.html", {"query_set": query_set})
django: In order to return a table row with the current users id in it, type
query_set = UserProfile.objects.get(user_id=request.user.id)
django: To return all of the rows in a model, type
Modelname.objects.all()
django: To query for model rows with a column less than or equal to 5, type
Modelname.objects.filter(column_name__lte=5)
django: When you query a model using “filter” it always returns a
query set.
django: To access an object within a query set you must
slice it.
django: When you query a model using “get” it always returns
an object instance, which does not require a slice to access attributes.
django: When using Modelname.objects.get(pk=3) it is preferable to use pk over id because
pk always refers to the primary key while id can have different names.
django: When adding the field to a UserProfile model that defines it’s relationship with a user, the best relationship it
models.OneToOneField(User)
django: To return all of the model rows with a column that has the (case sensitive) value “Column Value”, type
Modelname.objects.filter(column_name__exact=”Column Value”)
django: To return model rows who’s foreign key has a column that contains “Column Value”, type
Modelname.objects.filter(foreign_key_column__foreign_keys_column_name__contains = “Column Value”)
django: To be able to validate form fields and to create automated validation error messages you can
create forms for the models and then pass it in
django: The “sender” parameter the post_save signal allows you to specify
which specific databases saves you want to be triggered for.
django: The best way to create a User and UserProfile together is to
have a signal receiver that creates an instance of the profile model (related to the user instance) directly after saving it, and then using the current user instance to access the new UserProfile instance in reverse using the related to to set all the values like user.user_profile.attribute = request.POST.get(“attribute”, “”)
django: any time you create a models.OneToOne relationship, you must
provide the related_name, so that the attributes of the new model can be accessed in reverse using that name.
e.g.
user = models.OneToOneField(User, related_name=”user_profile”)
django: To create a signal receiver for saves to the User model that creates an instance of UserProfile that has a relationship to the current instance of User, type
into models.py
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User) def create_user_profile(sender, instance=None, created=False, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance)
django: To make model fields be allowed to be empty add the params
null=True, blank=True
django: If assigning model attributes in a view like user.attribute = “value”, remember to
save
Note: If altering a foreign model, call save on the foreign model. e.g.
model_instance.foreign_model.save()
django: the render() function automatically sends the template
the current “user” instance
django: To return the pk attribute of a user instance, type
user_instance.id
django: To create a way for users to view other users profiles, you can
turn the username of the users into links with a parameter that is their pk. Then if clicked urls.py will pass the desired users pk to the view which will get their User object and pass that to the template.
django: in {“query_set”: user_profile}, the variable that gets passed to the template is
query_set
django: The maximum recursion depth exceeded error happens if you
create a views that redirects causing two server hits.
regex: To specify the end of a string, type
$
django: When each type of user requires a very different type of layout it is best to
keep the display logic in the template.
django: To allow null values in a boolean field, use
models.NullBooleanField(null=True, blank=True)
django: To avoid being logged in with two users
open an incognito window for the admin.
django: django does not allow redirecting to another page because
that requires two server hits instead of just one if you recreate all the logic in the current view as well.
django: When using two ModelForms in the same form tag, to validate
use if form1.is_valid() and form2.is_valid()
django: To allow form validaiton errors to show, make sure to instantiate the forms
before you do the if request.method == “POST” so that if the forms are invalid the else will render the forms with the data in it in order to show the errors.
django: When creating a form, to ensure that validation error messages pass into the template make sure that
the forms are not reinstantiated without the request.POST data inside before being passed back into the view, so that they are passed with the data and able to render the errors.
django: To print form field validation errors in the template, type
{{ form_var.field_name.errors }}
{{ form_var2.field_name2.errors }}
django: I prefer to make the query_set I send in simply be
User.objects.filter(is_superuser=False) and then navigate to the necessary ralted column in the template.
django: To filter for all users that are not a superuser, type
User.objects.filter(is_superuser=False)
django: using the filter and get commands are not possible
inside templates
django: To save an image or files in the view, type
model_instance = Modelname()
model_instance.field_name = request.FILES.get(“name”)
model_instance.save()
django: To render an image from a model with an ImageField, type
-img src=”{{ model_instance.image_field.url }}” alt=””>
AWS: To create a distribution just
click in the field to get a list of your S3 endpoints or type bucketname.s3.amazonaws.com and submit the rest as default.
django: To set a model instances foreign key to a user you need to pass in
the request.user instance and not request.user.id
django: if you change or move the file that an active runserver or git is using
you must restart the server, otherwise it will serve incorrectly and cd out and back into the file, otherwise git will error.
django: When trying to show form errors in a template dont forget that
errors is plural
django: When in production you must set DEBUG to
False and set the ALLOWED_HOSTS = [“*”]
django: To render values from a query string directly in a template, type
{{ request.GET.key_name }}
html: When a form is also posting files, you must add the attribute
enctype=”multipart/form-data”
html: If you set action of a form to “” the form will
post to itself
html: If you set action of a form to “” the form will
post to itself
html: If you set action of a form to “” the form will
post to itself
django: To update an image upload only if there is something entered, type
if request.FILES.get(“image”):
model_instance.image_field = request.FILES.get(“image”)
model_instance.save()
django: To return the name of an image and its housing folder from a model instance, type
Model_instance.image_field.name
AWS: To get the aws access key and aws secret keys
Go to the IAM console, then click on the Users tab and then click on a user or create one.
AWS: To allow a user to access the API, you must
set the users policy to give him permissions.
AWS: To save a file to S3 using boto from the command line, type
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection(‘-aws access key>’, ‘-aws secret key>’, host=”s3-us-west-1.amazonaws.com”)
bucket = conn.get_bucket(‘-bucket name>’)
k = Key(bucket)
k.key = ‘path/file_name.png’
k.set_contents_from_filename(“path/file.png”)
(k.set_contents_from_file if file is loaded into a var)
boto: To set read only permission to Everyone, type
conn = S3Connection(‘-aws access key>’, ‘-aws secret key>’)
bucket = conn.get_bucket(‘-bucket name>’)
bucket.set_acl(‘public-read’, ‘path/file_name.png’)
boto: To best way to give each user their own folder and make sure that all filenames are unique is to type
filepath = str(request.user.id) + "/" + filename_function() k.key = filepath
django: you should keep your private keys (e.g. aws) in
settings.py and access them with
from django.conf import settings
settings.VARIABLE_NAME
django: When the styles are going to be very different on a template
create a {% block head %} inside the base template and in the current template import a totally new stylesheet.
django: right before using {% static “app_name/styles.css” %} in a template, always add
{% load staticfiles %}
django: If you change the settings.py during development
you must restart the server and migrate to load the changes
html: To create a dropdown field that can go into a form, type
- select name=”name” id=”id” class=”form-control”>
- option value=”“>Default-/option>
- option value=”Value 1”>Value 1-/option>
- /select>
django: To delete an a models record, type
model_instance = Modelname.objects.get(pk = id_number)
model_instance.delete()
django: To sort a query_set, append to the end
.order_by(“attribute”)
or
.order_by(“-attribute”)
django: To create a model row that belongs to another model row in the same table, type
parent_instance = models.ForeignKey(‘self’)
django: To create a query_set with an or statement, type
from django.db.models import Q
query_set = Modelname.objects.filter(Q(field=”value”) | Q(field=value))
django: To return the number of items in a query_set, type
Modelname.object.all().count()
django: To remove items in a query_set with a duplicate value in a column, type
query_set = Message.objects.all() seen = set() keep = [] for item in query_set: if item.field not in seen: keep.append(item) seen.add(item.field)
django: To paginate a query_set in a view, type
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
page = request.GET.get("page") paginator = Paginator(query_set, 10) try: page_set = paginator.page(page) except PageNotAnInteger: page_set = paginator.page(1) except EmptyPage: page_set = paginator.page(paginator.num_pages)
django: request.user is a
simplelazyobject, not a real user object
django: To pull in code from another template file, type
{% include “app_name/template_name.html” %}
note: Do not add blocks to the template being pulled in.
django: To set the url tag by giving it the view path instead of the url name, type
{% url “app_name.views.view_name” %}
django: When there is an error involving migrations, you can
delete all your migrations by in the migrations folder in the app and then makemigrations and migrate again from scratch
django: If you enter an invalid email recipient into django’s send_mail function, it will
not error
django: To remove some records that match a criteria from a query_set returned by a filter, type
Modelname.objects.filter(field=”value”).exclude(field=”value”)
django: remember that if you return a query set from .filter you
cannot access attributes of it, since it is a set and not an individual instance.
django: To return an attribute of a query set that states where or not a query set is empty, type
query_set.exists()
django: To make a django template if statement test for two things, use
and
django: To add a css class to a modelform, type
class MyForm(forms.ModelForm): field_name = forms.CharField(widget=forms.TextInput(attrs={"class" : "form-control"})) class Meta: model = Modelname fields = ["field_name"]
django: To insert default values into the form fields from the view, type
form = MyForm({“name”:”value”})
django: To create a custom form field validation, type
from django.core.exceptions import ValidationError
def my_validation1(value): if value == "value": raise ValidationError("String")
class MyForm(forms.ModelForm): field_name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}), validators=[my_validation1]) class Meta: model = Modelname fields = ["field_name"]
django: To validate a form and then add a field value to it before saving it, type
if form.is_valid():
obj = form.save(commit=False)
obj.field_name = “value”
obj.save()
django: To get the ip address of a request, type
pip install django-ipware
from ipware.ip import get_ip
in the view function-
ip = get_ip(request)
django: To create a textarea form field rather than a text input, type
field = forms.CharField(widget=forms.Textarea(attrs={‘class’ : ‘form-control’}))
django: forms.ChoiceField’s must get passed in
the param for choices which is a list of tuple pairs.
forms.ChoiceField(choices=[(“a”,”a”), (“b”, “b”)])
django: When using {{ form.field_name.errors }} it is best to place it
below the field
django: To create labels for your {{ form.form_field }}, type
-label for=”field_name”>Field Name:
django: To create a model field that takes integers, type
field_name = models.IntegerField(default=0)
django: To set the app to work with mysql on pythonanywhere
install mysqlclient into virtualenv
workon django18
pip install mysqlclient
in settings.py
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘your_username$your_database_name’,
‘USER’: ‘your_username’,
‘PASSWORD’: ‘your_mysql_password’,
‘HOST’: ‘mysql.server’,
}
}
In console
python manage.py makemigrations
python manage.py migrate
AWS: To save a file to S3 using boto from views.py, type
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from datetime import datetime
def filename_function(): return datetime.now().strftime("%Y-%m-%d-%S-%f") + ".png"
if request.FILES.get(“field”):
conn = S3Connection(“-aws_access-key>”, “-aws_secret_key>”)
bucket = conn.get_bucket(“-bucket_name>”)
k = Key(bucket)
filepath = filename_function()
k.key = filepath
k.set_contents_from_file(request.FILES.get(“field”))
bucket.set_acl(‘public-read’, filepath)
django: In order for a django form to validate files that you then save into a CharField and upload to s3, you must
make the form field a FileField
make the model field a CharField and
pass both the request.FILES and requests.POST arguments into the views form instance
create an obj = form.save(commit=False) and change the name of the file to the one on saves to s3
obj.save()
django: any time that you create a url that is r’^’, you should
put it last so the regex doesnt match another url
django: remember that you templates are held in a folder called
templates, not template
django: an apps templates can only use access the css files from
the same app, so you must add the path to the new apps css files in the base.html
django: To render a query sets attribute as html instead of as text, type
{{ query_set.attribute|safe }}
django: After a site is live I must always
have a local environment that is almost exactly the same that I can push to the server.
django: To create a django view, that returns addition query set objects through ajax, type
def view_function(request): query_set = Accessory.objects.all() if request.is_ajax(): page = request.GET.get("page") paginator = Paginator(query_set, 5) try: page_set = paginator.page(page) return render(request, "app_name/ajax_template.html", {"page_set": page_set}) except: return HttpResponse("") else: return render(request, "app_name/template_name.html", {"query_set":query_set[:5], "category_name":"Categories"})
Note: The paginated query set should be sent to its own template to be rendered and then sent without surrounding code.
django: In base.html you should have the blocks
head
content
js (after the sitewide imports)
pythonanywhere: When you change a static file
you must python manage.py collectstatic for the change to take effect
django: To force https in django you must
pip install –user django-sslify
add the middleware as the first middleware class
make sure that ALLOWED_HOSTS is set up properly
make sure that DEBUG = False
django: for security purposes you should
change the admins url, e.g. aadminn
django: To return a cookie value from within a django view function, type
request.COOKIES.get(‘key_name’)
godaddy: To change a cname
go to https://mya.godaddy.com/default.aspx
click “manage” on the desired domain
click on the DNS Zone File tab
pythonanywhere: When checking the error log
check the most recent which is at the bottom
pythonanywhere: After connecting settings.py to mysql
you must makemigrations and migrate
django: When debug = False, Django won’t
serve static files for you any more. Your production web server will have to do it.
django: To filter for records where the created_at field is between two values, type
from datetime import datetime, timedelta
now = datetime.now() before = datetime.now() - timedelta(minutes=15) query_set = Modelname.objects.filter(created_at\_\_range=(before, now))
django: Secret keys that you put in settings.py to later access through from django.conf import setting
must be all caps
django: To set a cookie with the rendering of a template, type
response = render(request, “app_name/template.html”)
response.set_cookie(key=’string’, value=’string’, max_age=60)
return response
pythonanywhere: To change the project folder my app points to
change the project name in the wsgi file and the static files path
django: To turn a dict of data into a json response, type
from django.http import JsonResponse return JsonResponse({'foo':'bar'})
django: To turn a query set into a dict and send it as a json response, type
from django.http import JsonResponse
from django.core import serializers
query_set = Modelname.objects.all() return JsonResponse(serializers.serialize('json', query_set), safe=False)
python: To sort a python list according to a key, type
sorted(my_iterable, key=lambda x: x[2])
python: The “key=” argument in sorted() is a
function that gets called on every item in the iterable and the return determines its order
json: if you get the error: TypeError: the JSON object must be str, not ‘bytes’ you need to
call .decode() on your variable containing json string
django: api auth keys are usually sent in the
header called “Authorization”: “Bearer xxx”
django: To save a form into a specific model instance that it already in the database, to update a model instance using a form, type
form = BrandProfileForm(request.POST, instance=model_instance)
form.save()
django: request.POST’s QueryDict is
immutable
django: To duplicate a model instance and save it, type
model_instance = Modelname.objects.get(pk=10)
model_instance.pk = None
model_instance.save()
django: To make sure a form that takes in an instance only overwrites certain fields
make sure the form itself only has the chosen fields in fields = [“field”,]
python: Some falsey values are
[], 0, None, False, “”
javascript: If accessing an objects key using square brackets, you must
use quotes
e.g.
myObject[“key”]
javascript: If you want to create a javascript object key name with a space in it, you must
use quotes
javascript: If you want to access a javascript object key name with a space in it, you must
use square brackets
javascript: To access attributes from within the class instance you are currently using, type
this.myAttribute
django: A serializer is
a function that transforms your data into another format e.g. json
django: To render a url with 2 parameters, type
{% url ‘url_name’ named_group=1 named_group2=2 %}
django: To print all the form errors together in the template, type
{{ form.non_field_errors }}
django: To make a view not check csrf_token, use
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
django: To render the number of objects that belong to current object, type
{{ object.lowercase_model_name_set.count }}
note: must add the _set to the modelname
django: The csrf token is the same for
for all the forms on the page
django: To use data passed in from the view in javascript without having to write all the scripts inside the template
create one script tag on the page that has all the necessary data rendered into variables inside it
import the script tags below it
django: To create a template tag
create a folder inside an app called templatetags
inside create and empty file called __init__.py
parallel to __init__ create a python file named whatever
inside type
from django import template
register = template.Library()
@register.filter
def filter_name(param1):
…
return “string”
note: before using a custome filter in the template you must load it
django: before using a custom filter in the template you must
{% load filter_name %}
django: To send the user a csv with query_set data, type
response = HttpResponse(content_type=’text/csv’)
response[‘Content-Disposition’] = ‘attachment; filename=”somefilename.csv”’
writer = csv.writer(response)
writer.writerow([‘column1’, ‘column2’])
for item in query_set:
writer.writerow([item.field1, item.field2])
return response
heroku: To ssh into your heroku app, type
heroku run bash
django: To have settings change when in development and when in production
vi ~/.bash_profile
add export DJANGO=”dev”
add to settings.py
if os.environ.get(‘DJANGO’) is not None:
overwrite_var = “value”
note: Changes to .bash files require the terminal to be restarted before taking effect
note: It’s best to put the sqlite database in this if, since mysqlclient wont work locally
cbv: How a DetailView works is
You use “pk” as that name of the parameter in the url that receive the records id, and then in the detail view model = ModelName will grab the variable called “pk” automatically and use that as the ID to look up in the model you choose. Then it passes that one object into the template.
cbv: A DeleteView knows which record to delete by
grabbing the variable named “pk” from the url and then looking up that ID in the model you provide.
allauth: To be able to use allauth without setting up smtp first, type
settings.py
EMAIL_BACKEND = ‘django.core.mail.backends.console.EmailBackend’
dra: to make dra work
add to apps ‘rest_framework.authtoken’
this works $.ajax({ method: 'post', url: '/rest-auth/login/', data: {email: 'email@gmail.com', password: 'string123'}, success: (r) => { console.log(r.key) } }) $.ajax({ method: 'get', url: '/rest-auth/user/', data: {username: 'alensw11+1'}, success: (r) => { console.log(r) }, headers: { 'Authorization':'Token 873adbad0f9ec441976eded0fe1d1cadfa8157ad', }, })
django: To debug to False in heroku environment
heroku config:set ON_HEROKU=1
if ON_HEROKU in os.environ:
return False
the benefit of using a with state (context manager), is
is automatically calls close on the file after the block runs.
file = open('file.txt', 'w') try: file.write('string') finally: file.close()
vs
with open('file.txt', 'w') as file: file.write('string')
to run a function on each line of a csv without loading into memory, type
with open("file.txt", "r") as file: for line in file: do_something_with(line.split(', '))
python: map does not
run in place, must assign the return to a variable
python: range(3) return
[0, 1, 2]
python: To convert a list of intergers to strings, type
new_list = [str(item) for item in [1,2,3]]
or
new_list = map(lambda x: str(x), [1,2,3])
python: To join a list of strings with a separator, type
’, ‘.join(my_list)
python: 5 > None will return
True
python: before writing every function
write a comment of what you want the function to do above
then as you write it use (python 3’s) print(f”var_name: {var_name}”) in the function for easy debugging.
django: to send a blob to django, type
@csrf_exempt def electron(request): print(request.FILES.get('image', 'default') ) return HttpResponse('{"hi": 4}')
toBlob(fs.createReadStream(‘./pic.png’), function (err, blob) {
if (err) return console.error(err.message)
var formData = new FormData();
formData.append(“field_name”, blob, ‘filename.png’);
fetch(http://127.0.0.1:8000/electron
, {
method: ‘POST’,
body: formData
})
.then((response) => response.json() )
.then( (data)=> console.log(data.hi) )
})
FormData() is used
just like the regular {} object in the ajax payload, but it allows for files, while a regular object does not. It is always better.
@login_required does not work for
django rest framework style authentication
drf: To send an authenticated request to drf on a function view
settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), }
let formData = new FormData(); formData.append("screenshot", res, 'screenshot.png');
fetch(`http://127.0.0.1:8000/upload_screenshot/`, { method: 'POST', body: formData, headers: new Headers({ 'Authorization': 'Token ' + authKey, }) }) .then((response) => response.json()) .then((data)=> console.log(data))
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
@api_view(['GET', 'POST']) @permission_classes((IsAuthenticated, )) def upload_screenshot(request): return Response({"string": "string"})
also, follow the regular installation from dango rest AUTH.
django-storages: To save an image, type
image_model_instance = ImageModel()
image_model_instance.image_field.save(‘aws_name.jpg’, open(‘/users/student/desktop/img.jpg’,”rb”))
image_model_instance.image_field.url
> returns the url (need to make sure each url is unique so its not overwritten)
when setting up allauth, make sure
you set the site ad ID 1 to http://localhost:8000/ . I was making a mistake putting it at 127.0.0.0:8000 but then my callback url in linkedin was to localhost:8000 and that cause an error. The callback url and the site name need to be the same. The login doesn’t work when I try to log in from 127.0.0.0:8000, just localhost.
drf: A drf auth token is valid for
forever
https://stackoverflow.com/questions/22943050/how-long-is-token-valid-django-rest-framework
mac app:
To make a mac app distribution, your membership must be up to date
to have nested objects inside a serializer
https://stackoverflow.com/questions/14938895/serializer-dealing-with-nested-objects
and to have them nested but with a reverse relationship list of objects
https://stackoverflow.com/questions/14573102/how-do-i-include-related-model-fields-using-django-rest-framework