Django Flashcards

1
Q

heroku: To open your app in the browser, type

A

heroku open

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

django: To import HttpResponse, type

A

from django.http import HttpResponse

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

django: Inside of urls.py you need to import

A

from . import views

or from .views import *

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

django: By convention, model names should be

A

singular

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

django: App names are usually

A

the plural of the main model your app will be about.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

django: To create database entries from the django shell, type

A

from app_name.models import Modelname

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

django: To access the database from within views.py, type

A

from .models import Model

from .models import *

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

django: To create a urls.py

A

from django.urls import path, include

urlpatterns = [
path(‘url’, views.view_name, name=”string”),
]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

django: To create templates for an app, you need to first

A

create a templates folder inside the app and another folder inside the templates folder with the same name as the app.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

django: To create templates for an app, you need to first

A

create a templates folder inside the app.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

django: To render a template from a view function, type

A

return render(request, “app_name/template.html”, {“pass_in_var”: local_var})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

django: To tell django where to look for static files

A

go to settings.py and type
STATICFILES_DIRS = (
os.path.join(BASE_DIR, “assets”),
)

note: must have trailing comma

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

django: To specify a one to many relationship in a model, type

A

other_model = models.ForeignKey(OtherModel)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

django: When you create a new model and want to include it in the admin area, you must

A

include it in this apps admin.py file.

from .models import Modelname

admin.site.register(Modelname)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

django: To install django, type

A

pip install django

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

django: The stub is

A

the app-like folder automatically created django that holds site wide files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Html: the form tags must have the two attributes

A

The type of http method to use (post or get)

The url to send the data to.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

django: The python manage.py makemigrations command makes migrations for all of the

A

installed apps in settings.py

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

django: In the django shell, before you can add new instances you need to import the model by typing

A

from app_name.models import Modelname

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

django: When creating new models, it is usefull to add the __str__ method so that

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

django: When adding new urls to a urls.py file, remember to start it with

A

url(

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

django: urls that are assigned in an apps urls.py are

A

appended to the to the url assigned in the stubs site wide urls.py

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

django: pk stands for

A

primary key (it is the id of the record that is automatically generated by django)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

django: when creating an html template, model.step_set.all does not require

A

brackets

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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 %}
26
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.
27
Errors on the server should always generate the error page numbered
500
28
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... ```
29
django: So the parameters are captured properly, you must order the urls in urls.py from
most parameters to least.
30
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")),
31
django: To reference a url based on its set name from inside an html template, type
namespace:url_name
32
re: To make a character optional, type
? after it
33
django: django forms do not automatically render the
form tags. Only the input tags.
34
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}) ```
35
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> ```
36
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) ```
37
django: columns that are auto generated (like created at) should not
be added as a field to a ModelForm
38
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}) ```
39
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.
40
django: The user model is
automatically created.
41
django: To import the User model, type
from django.contrib.auth.models import User
42
django: When inheriting from the UserCreationForm, it is prohibited to not
supply fields in the meta class
43
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"] ```
44
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})
45
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 ...
46
django: The templates for the django.contrib.auth.views must be
created manually.
47
django: the logout url from the django.contrib.auth.views, by default, looks for the template in
templates/registration/logged_out.html
48
django: the login url from the django.contrib.auth.views, by default, looks for the template in
templates/registration/login.html
49
django: all of the django.contrib.auth.views pass a variable to the template called
form
50
django: the password_change url from the django.contrib.auth.views, by default, looks for the template in
templates/registration/password_change_form.html
51
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
52
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')) ]
53
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) ```
54
django: when using the include() function inside of url() remember to
put quotes around the path to the app urls.
55
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 ```
56
django: It is not HttpRequest(), it is
HttpResponse()
57
django: The action for the form in the login.html template should be
-form method="post" action="{% url 'django.contrib.auth.views.login' %}">
58
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
59
django: The path for static files should be
project_name/app_name/static/app_name/styles.css
60
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
61
django: To return the key value if your url is www.example.com/?key=value, type
request.GET.get("key", "")
62
django: To include the custom stylesheet in django, type
{% load staticfiles %} | -link rel="stylesheet" href="{% static "app_name/styles.css" %}">
63
django: The fields you specify in your UserCreationForm must
exactly match the input names in your templates form.
64
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'} ), ]
65
django: you must place base.html in
the templates folder, not with all the other html files.
66
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.
67
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"}), } ```
68
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)
69
django: The mandatory parameter for models.CharField() is
max_length=100
70
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 %} ```
71
pythonanywhere allows you to
schedule scripts
72
django: To exclude a field from the generated form in forms.py, type
``` class Meta: model = Modelname exclude = ['field1'] ```
73
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
74
django: To wipe all data from the database, type
python manage.py flush
75
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) ```
76
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") ```
77
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}) ```
78
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)
79
django: To return all of the rows in a model, type
Modelname.objects.all()
80
django: To query for model rows with a column less than or equal to 5, type
Modelname.objects.filter(column_name__lte=5)
81
django: When you query a model using "filter" it always returns a
query set.
82
django: To access an object within a query set you must
slice it.
83
django: When you query a model using "get" it always returns
an object instance, which does not require a slice to access attributes.
84
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.
85
django: When adding the field to a UserProfile model that defines it's relationship with a user, the best relationship it
models.OneToOneField(User)
86
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")
87
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")
88
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
89
django: The "sender" parameter the post_save signal allows you to specify
which specific databases saves you want to be triggered for.
90
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", "")
91
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")
92
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) ```
93
django: To make model fields be allowed to be empty add the params
null=True, blank=True
94
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()
95
django: the render() function automatically sends the template
the current "user" instance
96
django: To return the pk attribute of a user instance, type
user_instance.id
97
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.
98
django: in {"query_set": user_profile}, the variable that gets passed to the template is
query_set
99
django: The maximum recursion depth exceeded error happens if you
create a views that redirects causing two server hits.
100
regex: To specify the end of a string, type
$
101
django: When each type of user requires a very different type of layout it is best to
keep the display logic in the template.
102
django: To allow null values in a boolean field, use
models.NullBooleanField(null=True, blank=True)
103
django: To avoid being logged in with two users
open an incognito window for the admin.
104
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.
105
django: When using two ModelForms in the same form tag, to validate
use if form1.is_valid() and form2.is_valid()
106
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.
107
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.
108
django: To print form field validation errors in the template, type
{{ form_var.field_name.errors }} | {{ form_var2.field_name2.errors }}
109
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.
110
django: To filter for all users that are not a superuser, type
User.objects.filter(is_superuser=False)
111
django: using the filter and get commands are not possible
inside templates
112
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()
113
django: To render an image from a model with an ImageField, type
-img src="{{ model_instance.image_field.url }}" alt="">
114
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.
115
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
116
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.
117
django: When trying to show form errors in a template dont forget that
errors is plural
118
django: When in production you must set DEBUG to
False and set the ALLOWED_HOSTS = ["*"]
119
django: To render values from a query string directly in a template, type
{{ request.GET.key_name }}
120
html: When a form is also posting files, you must add the attribute
enctype="multipart/form-data"
121
html: If you set action of a form to "" the form will
post to itself
122
html: If you set action of a form to "" the form will
post to itself
123
html: If you set action of a form to "" the form will
post to itself
124
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()
125
django: To return the name of an image and its housing folder from a model instance, type
Model_instance.image_field.name
126
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.
127
AWS: To allow a user to access the API, you must
set the users policy to give him permissions.
128
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)
129
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')
130
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 ```
131
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
132
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.
133
django: right before using {% static "app_name/styles.css" %} in a template, always add
{% load staticfiles %}
134
django: If you change the settings.py during development
you must restart the server and migrate to load the changes
135
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>
136
django: To delete an a models record, type
model_instance = Modelname.objects.get(pk = id_number) | model_instance.delete()
137
django: To sort a query_set, append to the end
.order_by("attribute") or .order_by("-attribute")
138
django: To create a model row that belongs to another model row in the same table, type
parent_instance = models.ForeignKey('self')
139
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))
140
django: To return the number of items in a query_set, type
Modelname.object.all().count()
141
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) ```
142
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) ```
143
django: request.user is a
simplelazyobject, not a real user object
144
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.
145
django: To set the url tag by giving it the view path instead of the url name, type
{% url "app_name.views.view_name" %}
146
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
147
django: If you enter an invalid email recipient into django's send_mail function, it will
not error
148
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")
149
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.
150
django: To return an attribute of a query set that states where or not a query set is empty, type
query_set.exists()
151
django: To make a django template if statement test for two things, use
and
152
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"] ```
153
django: To insert default values into the form fields from the view, type
form = MyForm({"name":"value"})
154
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"] ```
155
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()
156
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)
157
django: To create a textarea form field rather than a text input, type
field = forms.CharField(widget=forms.Textarea(attrs={'class' : 'form-control'}))
158
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")])
159
django: When using {{ form.field_name.errors }} it is best to place it
below the field
160
django: To create labels for your {{ form.form_field }}, type
-label for="field_name">Field Name:
161
django: To create a model field that takes integers, type
field_name = models.IntegerField(default=0)
162
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
163
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)
164
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()
165
django: any time that you create a url that is r'^', you should
put it last so the regex doesnt match another url
166
django: remember that you templates are held in a folder called
templates, not template
167
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
168
django: To render a query sets attribute as html instead of as text, type
{{ query_set.attribute|safe }}
169
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.
170
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.
171
django: In base.html you should have the blocks
head content js (after the sitewide imports)
172
pythonanywhere: When you change a static file
you must python manage.py collectstatic for the change to take effect
173
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
174
django: for security purposes you should
change the admins url, e.g. aadminn
175
django: To return a cookie value from within a django view function, type
request.COOKIES.get('key_name')
176
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
177
pythonanywhere: When checking the error log
check the most recent which is at the bottom
178
pythonanywhere: After connecting settings.py to mysql
you must makemigrations and migrate
179
django: When debug = False, Django won't
serve static files for you any more. Your production web server will have to do it.
180
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)) ```
181
django: Secret keys that you put in settings.py to later access through from django.conf import setting
must be all caps
182
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
183
pythonanywhere: To change the project folder my app points to
change the project name in the wsgi file and the static files path
184
django: To turn a dict of data into a json response, type
``` from django.http import JsonResponse return JsonResponse({'foo':'bar'}) ```
185
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) ```
186
python: To sort a python list according to a key, type
sorted(my_iterable, key=lambda x: x[2])
187
python: The "key=" argument in sorted() is a
function that gets called on every item in the iterable and the return determines its order
188
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
189
django: api auth keys are usually sent in the
header called "Authorization": "Bearer xxx"
190
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()
191
django: request.POST's QueryDict is
immutable
192
django: To duplicate a model instance and save it, type
model_instance = Modelname.objects.get(pk=10) model_instance.pk = None model_instance.save()
193
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",]
194
python: Some falsey values are
[], 0, None, False, ""
195
javascript: If accessing an objects key using square brackets, you must
use quotes e.g. myObject["key"]
196
javascript: If you want to create a javascript object key name with a space in it, you must
use quotes
197
javascript: If you want to access a javascript object key name with a space in it, you must
use square brackets
198
javascript: To access attributes from within the class instance you are currently using, type
this.myAttribute
199
django: A serializer is
a function that transforms your data into another format e.g. json
200
django: To render a url with 2 parameters, type
{% url 'url_name' named_group=1 named_group2=2 %}
201
django: To print all the form errors together in the template, type
{{ form.non_field_errors }}
202
django: To make a view not check csrf_token, use
from django.views.decorators.csrf import csrf_exempt @csrf_exempt
203
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
204
django: The csrf token is the same for
for all the forms on the page
205
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
206
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
207
django: before using a custom filter in the template you must
{% load filter_name %}
208
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
209
heroku: To ssh into your heroku app, type
heroku run bash
210
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
211
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.
212
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.
213
allauth: To be able to use allauth without setting up smtp first, type
settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
214
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', }, }) ```
215
django: To debug to False in heroku environment
heroku config:set ON_HEROKU=1 if ON_HEROKU in os.environ: return False
216
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') ```
217
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(', ')) ```
218
python: map does not
run in place, must assign the return to a variable
219
python: range(3) return
[0, 1, 2]
220
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])
221
python: To join a list of strings with a separator, type
', '.join(my_list)
222
python: 5 > None will return
True
223
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.
224
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) ) })
225
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.
226
@login_required does not work for
django rest framework style authentication
227
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.
228
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)
229
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.
230
drf: A drf auth token is valid for
forever | https://stackoverflow.com/questions/22943050/how-long-is-token-valid-django-rest-framework
231
mac app:
To make a mac app distribution, your membership must be up to date
232
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