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
Q

django: when creating an html template, to loop through models related records from it’s foreign key, type

A

{% for item in model.step_set.all %}
item.name
{% endfor %}

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

django: To make the return of Modelname.objects.all() come out in a specific order, you must add the following to the model:

A
class Meta()
    ordering = ["my_attribute",]

Note: more ordering columns can be added to the list.

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

Errors on the server should always generate the error page numbered

A

500

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

django: To throw a 404 when a bad url is used, type

A

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...
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

django: So the parameters are captured properly, you must order the urls in urls.py from

A

most parameters to least.

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

django: To give a url a name and set the namespace, type

A

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”)),

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

django: To reference a url based on its set name from inside an html template, type

A

namespace:url_name

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

re: To make a character optional, type

A

? after it

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

django: django forms do not automatically render the

A

form tags. Only the input tags.

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

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

A

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})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

django: To create a django form or model form in a template, type

A
-form action="/page/" method="post">
    {% csrf_token %}
    {{ form }}
    -input type="submit" value="Submit" />
-/form>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

django: To create a form that does not interact with the database, type

A

in forms.py

from django import forms

class MyForm(forms.Form):
    name = forms.CharField(label='Name', max_length=100)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

django: columns that are auto generated (like created at) should not

A

be added as a field to a ModelForm

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

django: To create a ModelForm that saves to the database, type

A

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})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

django: When you need a form with some fields that save to separate other models, you need to

A

create both forms and include them in the views form tags together. Then validate both of them before saving.

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

django: The user model is

A

automatically created.

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

django: To import the User model, type

A

from django.contrib.auth.models import User

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

django: When inheriting from the UserCreationForm, it is prohibited to not

A

supply fields in the meta class

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

django: To create a user registration form with username, email, and password confirmation, type

A

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ["username", "email"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

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

A

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})

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

django: To make a view check whether or not a user is authenticated/logged in, type

A

if request.user.is_authenticated():
return …

if not request.user.is_authenticated():
return …

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

django: The templates for the django.contrib.auth.views must be

A

created manually.

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

django: the logout url from the django.contrib.auth.views, by default, looks for the template in

A

templates/registration/logged_out.html

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

django: the login url from the django.contrib.auth.views, by default, looks for the template in

A

templates/registration/login.html

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

django: all of the django.contrib.auth.views pass a variable to the template called

A

form

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

django: the password_change url from the django.contrib.auth.views, by default, looks for the template in

A

templates/registration/password_change_form.html

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

django: When using the django.contrib.auth.views login url, if the login is successful, and there is no “next” variable, it redirects to

A

settings.LOGIN_REDIRECT_URL

and if that is not set, then accounts/profile

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

django: To use all of the django.contrib.auth.urls urls, type

A

from django.conf.urls import include, url

urlpatterns = [
url(r’^’, include(‘django.contrib.auth.urls’))
]

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

django: To add extra columns to the default User model, type

A

from django.contrib.auth.models import User

class Modelname(models.Model):
    user = models.OneToOneField(User)
    column1 = models.CharField(max_length=100)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

django: when using the include() function inside of url() remember to

A

put quotes around the path to the app urls.

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

django: The sequence of steps you must take to create a new app is

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

django: It is not HttpRequest(), it is

A

HttpResponse()

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

django: The action for the form in the login.html template should be

A

-form method=”post” action=”{% url ‘django.contrib.auth.views.login’ %}”>

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

django: When importing styles.css make the href path by typing

A

{% load staticfiles %}
-link rel=”stylesheet” href=”{% static “app_name/styles.css” %}”>

Note: Do not start path with slash

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

django: The path for static files should be

A

project_name/app_name/static/app_name/styles.css

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

django: in order to set the form action to action=”{% url “url_name” %}” you must fist

A

add name=”url_name” to the url in urls.py

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

django: To return the key value if your url is www.example.com/?key=value, type

A

request.GET.get(“key”, “”)

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

django: To include the custom stylesheet in django, type

A

{% load staticfiles %}

-link rel=”stylesheet” href=”{% static “app_name/styles.css” %}”>

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

django: The fields you specify in your UserCreationForm must

A

exactly match the input names in your templates form.

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

django: To set one django.contrib.auth view to have a custom template name, type

A

urlpatterns = [
url(r’^login’, django.contrib.auth.views.login, {‘template_name’: ‘login_template.html’} ),
]

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

django: you must place base.html in

A

the templates folder, not with all the other html files.

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

a virtualenv is

A

a package on the same server that is separate from the main one so you can use two versions of django together.

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

django: To add a class to a form field in a model form, type

A
class MyModelForm(models.ModelForm):
    class Meta:
        model = Modelname
        widgets = {
            'my_field': TextInput(attrs={"class": "myclass"}),
        }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

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

A

from django.middleware.csrf import get_token

def user_creation_view(request):
if request.method == “POST”:
form = UserForm(request.POST)
get_token(request)

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

django: The mandatory parameter for models.CharField() is

A

max_length=100

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

django: To create an if statement in a template that displays the username if logged in or says “Log in”, type

A
{% if user.is_authenticated %}
    Hey, {{ request.user.username }}
{% else %}
    Log In
{% endif %}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

pythonanywhere allows you to

A

schedule scripts

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

django: To exclude a field from the generated form in forms.py, type

A
class Meta:
        model = Modelname
        exclude = ['field1']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

django: Remember 3 things

A

always put a comma at the end of urls, and always write a == in if request.method == “POST”:, migrate after model changes

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

django: To wipe all data from the database, type

A

python manage.py flush

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

django: An alternative to saving a form in order to create a new user is

A
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = User.objects.create_user(username=username, password=password)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

django: To recieve a post request with a user registration and a couple UserProfile fields and create the relationship between them, type

A
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")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

django: To create a view that passes in an object for the User that is currently authenticated, type

A
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})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

django: In order to return a table row with the current users id in it, type

A

query_set = UserProfile.objects.get(user_id=request.user.id)

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

django: To return all of the rows in a model, type

A

Modelname.objects.all()

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

django: To query for model rows with a column less than or equal to 5, type

A

Modelname.objects.filter(column_name__lte=5)

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

django: When you query a model using “filter” it always returns a

A

query set.

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

django: To access an object within a query set you must

A

slice it.

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

django: When you query a model using “get” it always returns

A

an object instance, which does not require a slice to access attributes.

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

django: When using Modelname.objects.get(pk=3) it is preferable to use pk over id because

A

pk always refers to the primary key while id can have different names.

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

django: When adding the field to a UserProfile model that defines it’s relationship with a user, the best relationship it

A

models.OneToOneField(User)

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

django: To return all of the model rows with a column that has the (case sensitive) value “Column Value”, type

A

Modelname.objects.filter(column_name__exact=”Column Value”)

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

django: To return model rows who’s foreign key has a column that contains “Column Value”, type

A

Modelname.objects.filter(foreign_key_column__foreign_keys_column_name__contains = “Column Value”)

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

django: To be able to validate form fields and to create automated validation error messages you can

A

create forms for the models and then pass it in

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

django: The “sender” parameter the post_save signal allows you to specify

A

which specific databases saves you want to be triggered for.

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

django: The best way to create a User and UserProfile together is to

A

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”, “”)

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

django: any time you create a models.OneToOne relationship, you must

A

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”)

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

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

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

django: To make model fields be allowed to be empty add the params

A

null=True, blank=True

94
Q

django: If assigning model attributes in a view like user.attribute = “value”, remember to

A

save
Note: If altering a foreign model, call save on the foreign model. e.g.

model_instance.foreign_model.save()

95
Q

django: the render() function automatically sends the template

A

the current “user” instance

96
Q

django: To return the pk attribute of a user instance, type

A

user_instance.id

97
Q

django: To create a way for users to view other users profiles, you can

A

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
Q

django: in {“query_set”: user_profile}, the variable that gets passed to the template is

A

query_set

99
Q

django: The maximum recursion depth exceeded error happens if you

A

create a views that redirects causing two server hits.

100
Q

regex: To specify the end of a string, type

A

$

101
Q

django: When each type of user requires a very different type of layout it is best to

A

keep the display logic in the template.

102
Q

django: To allow null values in a boolean field, use

A

models.NullBooleanField(null=True, blank=True)

103
Q

django: To avoid being logged in with two users

A

open an incognito window for the admin.

104
Q

django: django does not allow redirecting to another page because

A

that requires two server hits instead of just one if you recreate all the logic in the current view as well.

105
Q

django: When using two ModelForms in the same form tag, to validate

A

use if form1.is_valid() and form2.is_valid()

106
Q

django: To allow form validaiton errors to show, make sure to instantiate the forms

A

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
Q

django: When creating a form, to ensure that validation error messages pass into the template make sure that

A

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
Q

django: To print form field validation errors in the template, type

A

{{ form_var.field_name.errors }}

{{ form_var2.field_name2.errors }}

109
Q

django: I prefer to make the query_set I send in simply be

A

User.objects.filter(is_superuser=False) and then navigate to the necessary ralted column in the template.

110
Q

django: To filter for all users that are not a superuser, type

A

User.objects.filter(is_superuser=False)

111
Q

django: using the filter and get commands are not possible

A

inside templates

112
Q

django: To save an image or files in the view, type

A

model_instance = Modelname()
model_instance.field_name = request.FILES.get(“name”)
model_instance.save()

113
Q

django: To render an image from a model with an ImageField, type

A

-img src=”{{ model_instance.image_field.url }}” alt=””>

114
Q

AWS: To create a distribution just

A

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
Q

django: To set a model instances foreign key to a user you need to pass in

A

the request.user instance and not request.user.id

116
Q

django: if you change or move the file that an active runserver or git is using

A

you must restart the server, otherwise it will serve incorrectly and cd out and back into the file, otherwise git will error.

117
Q

django: When trying to show form errors in a template dont forget that

A

errors is plural

118
Q

django: When in production you must set DEBUG to

A

False and set the ALLOWED_HOSTS = [“*”]

119
Q

django: To render values from a query string directly in a template, type

A

{{ request.GET.key_name }}

120
Q

html: When a form is also posting files, you must add the attribute

A

enctype=”multipart/form-data”

121
Q

html: If you set action of a form to “” the form will

A

post to itself

122
Q

html: If you set action of a form to “” the form will

A

post to itself

123
Q

html: If you set action of a form to “” the form will

A

post to itself

124
Q

django: To update an image upload only if there is something entered, type

A

if request.FILES.get(“image”):
model_instance.image_field = request.FILES.get(“image”)
model_instance.save()

125
Q

django: To return the name of an image and its housing folder from a model instance, type

A

Model_instance.image_field.name

126
Q

AWS: To get the aws access key and aws secret keys

A

Go to the IAM console, then click on the Users tab and then click on a user or create one.

127
Q

AWS: To allow a user to access the API, you must

A

set the users policy to give him permissions.

128
Q

AWS: To save a file to S3 using boto from the command line, type

A

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
Q

boto: To set read only permission to Everyone, type

A

conn = S3Connection(‘-aws access key>’, ‘-aws secret key>’)
bucket = conn.get_bucket(‘-bucket name>’)
bucket.set_acl(‘public-read’, ‘path/file_name.png’)

130
Q

boto: To best way to give each user their own folder and make sure that all filenames are unique is to type

A
filepath = str(request.user.id) + "/" + filename_function()
k.key = filepath
131
Q

django: you should keep your private keys (e.g. aws) in

A

settings.py and access them with
from django.conf import settings
settings.VARIABLE_NAME

132
Q

django: When the styles are going to be very different on a template

A

create a {% block head %} inside the base template and in the current template import a totally new stylesheet.

133
Q

django: right before using {% static “app_name/styles.css” %} in a template, always add

A

{% load staticfiles %}

134
Q

django: If you change the settings.py during development

A

you must restart the server and migrate to load the changes

135
Q

html: To create a dropdown field that can go into a form, type

A
  • select name=”name” id=”id” class=”form-control”>
  • option value=”“>Default-/option>
  • option value=”Value 1”>Value 1-/option>
  • /select>
136
Q

django: To delete an a models record, type

A

model_instance = Modelname.objects.get(pk = id_number)

model_instance.delete()

137
Q

django: To sort a query_set, append to the end

A

.order_by(“attribute”)
or
.order_by(“-attribute”)

138
Q

django: To create a model row that belongs to another model row in the same table, type

A

parent_instance = models.ForeignKey(‘self’)

139
Q

django: To create a query_set with an or statement, type

A

from django.db.models import Q

query_set = Modelname.objects.filter(Q(field=”value”) | Q(field=value))

140
Q

django: To return the number of items in a query_set, type

A

Modelname.object.all().count()

141
Q

django: To remove items in a query_set with a duplicate value in a column, type

A
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
Q

django: To paginate a query_set in a view, type

A

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
Q

django: request.user is a

A

simplelazyobject, not a real user object

144
Q

django: To pull in code from another template file, type

A

{% include “app_name/template_name.html” %}

note: Do not add blocks to the template being pulled in.

145
Q

django: To set the url tag by giving it the view path instead of the url name, type

A

{% url “app_name.views.view_name” %}

146
Q

django: When there is an error involving migrations, you can

A

delete all your migrations by in the migrations folder in the app and then makemigrations and migrate again from scratch

147
Q

django: If you enter an invalid email recipient into django’s send_mail function, it will

A

not error

148
Q

django: To remove some records that match a criteria from a query_set returned by a filter, type

A

Modelname.objects.filter(field=”value”).exclude(field=”value”)

149
Q

django: remember that if you return a query set from .filter you

A

cannot access attributes of it, since it is a set and not an individual instance.

150
Q

django: To return an attribute of a query set that states where or not a query set is empty, type

A

query_set.exists()

151
Q

django: To make a django template if statement test for two things, use

A

and

152
Q

django: To add a css class to a modelform, type

A
class MyForm(forms.ModelForm):
	field_name = forms.CharField(widget=forms.TextInput(attrs={"class" : "form-control"}))
	class Meta:
		model = Modelname
		fields = ["field_name"]
153
Q

django: To insert default values into the form fields from the view, type

A

form = MyForm({“name”:”value”})

154
Q

django: To create a custom form field validation, type

A

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
Q

django: To validate a form and then add a field value to it before saving it, type

A

if form.is_valid():
obj = form.save(commit=False)
obj.field_name = “value”
obj.save()

156
Q

django: To get the ip address of a request, type

A

pip install django-ipware

from ipware.ip import get_ip

in the view function-

ip = get_ip(request)

157
Q

django: To create a textarea form field rather than a text input, type

A

field = forms.CharField(widget=forms.Textarea(attrs={‘class’ : ‘form-control’}))

158
Q

django: forms.ChoiceField’s must get passed in

A

the param for choices which is a list of tuple pairs.

forms.ChoiceField(choices=[(“a”,”a”), (“b”, “b”)])

159
Q

django: When using {{ form.field_name.errors }} it is best to place it

A

below the field

160
Q

django: To create labels for your {{ form.form_field }}, type

A

-label for=”field_name”>Field Name:

161
Q

django: To create a model field that takes integers, type

A

field_name = models.IntegerField(default=0)

162
Q

django: To set the app to work with mysql on pythonanywhere

A

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
Q

AWS: To save a file to S3 using boto from views.py, type

A

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
Q

django: In order for a django form to validate files that you then save into a CharField and upload to s3, you must

A

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
Q

django: any time that you create a url that is r’^’, you should

A

put it last so the regex doesnt match another url

166
Q

django: remember that you templates are held in a folder called

A

templates, not template

167
Q

django: an apps templates can only use access the css files from

A

the same app, so you must add the path to the new apps css files in the base.html

168
Q

django: To render a query sets attribute as html instead of as text, type

A

{{ query_set.attribute|safe }}

169
Q

django: After a site is live I must always

A

have a local environment that is almost exactly the same that I can push to the server.

170
Q

django: To create a django view, that returns addition query set objects through ajax, type

A
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
Q

django: In base.html you should have the blocks

A

head
content
js (after the sitewide imports)

172
Q

pythonanywhere: When you change a static file

A

you must python manage.py collectstatic for the change to take effect

173
Q

django: To force https in django you must

A

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
Q

django: for security purposes you should

A

change the admins url, e.g. aadminn

175
Q

django: To return a cookie value from within a django view function, type

A

request.COOKIES.get(‘key_name’)

176
Q

godaddy: To change a cname

A

go to https://mya.godaddy.com/default.aspx
click “manage” on the desired domain
click on the DNS Zone File tab

177
Q

pythonanywhere: When checking the error log

A

check the most recent which is at the bottom

178
Q

pythonanywhere: After connecting settings.py to mysql

A

you must makemigrations and migrate

179
Q

django: When debug = False, Django won’t

A

serve static files for you any more. Your production web server will have to do it.

180
Q

django: To filter for records where the created_at field is between two values, type

A

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
Q

django: Secret keys that you put in settings.py to later access through from django.conf import setting

A

must be all caps

182
Q

django: To set a cookie with the rendering of a template, type

A

response = render(request, “app_name/template.html”)
response.set_cookie(key=’string’, value=’string’, max_age=60)
return response

183
Q

pythonanywhere: To change the project folder my app points to

A

change the project name in the wsgi file and the static files path

184
Q

django: To turn a dict of data into a json response, type

A
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
185
Q

django: To turn a query set into a dict and send it as a json response, type

A

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
Q

python: To sort a python list according to a key, type

A

sorted(my_iterable, key=lambda x: x[2])

187
Q

python: The “key=” argument in sorted() is a

A

function that gets called on every item in the iterable and the return determines its order

188
Q

json: if you get the error: TypeError: the JSON object must be str, not ‘bytes’ you need to

A

call .decode() on your variable containing json string

189
Q

django: api auth keys are usually sent in the

A

header called “Authorization”: “Bearer xxx”

190
Q

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

A

form = BrandProfileForm(request.POST, instance=model_instance)
form.save()

191
Q

django: request.POST’s QueryDict is

A

immutable

192
Q

django: To duplicate a model instance and save it, type

A

model_instance = Modelname.objects.get(pk=10)
model_instance.pk = None
model_instance.save()

193
Q

django: To make sure a form that takes in an instance only overwrites certain fields

A

make sure the form itself only has the chosen fields in fields = [“field”,]

194
Q

python: Some falsey values are

A

[], 0, None, False, “”

195
Q

javascript: If accessing an objects key using square brackets, you must

A

use quotes
e.g.
myObject[“key”]

196
Q

javascript: If you want to create a javascript object key name with a space in it, you must

A

use quotes

197
Q

javascript: If you want to access a javascript object key name with a space in it, you must

A

use square brackets

198
Q

javascript: To access attributes from within the class instance you are currently using, type

A

this.myAttribute

199
Q

django: A serializer is

A

a function that transforms your data into another format e.g. json

200
Q

django: To render a url with 2 parameters, type

A

{% url ‘url_name’ named_group=1 named_group2=2 %}

201
Q

django: To print all the form errors together in the template, type

A

{{ form.non_field_errors }}

202
Q

django: To make a view not check csrf_token, use

A

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt

203
Q

django: To render the number of objects that belong to current object, type

A

{{ object.lowercase_model_name_set.count }}

note: must add the _set to the modelname

204
Q

django: The csrf token is the same for

A

for all the forms on the page

205
Q

django: To use data passed in from the view in javascript without having to write all the scripts inside the template

A

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
Q

django: To create a template tag

A

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
Q

django: before using a custom filter in the template you must

A

{% load filter_name %}

208
Q

django: To send the user a csv with query_set data, type

A

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
Q

heroku: To ssh into your heroku app, type

A

heroku run bash

210
Q

django: To have settings change when in development and when in production

A

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
Q

cbv: How a DetailView works is

A

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
Q

cbv: A DeleteView knows which record to delete by

A

grabbing the variable named “pk” from the url and then looking up that ID in the model you provide.

213
Q

allauth: To be able to use allauth without setting up smtp first, type

A

settings.py

EMAIL_BACKEND = ‘django.core.mail.backends.console.EmailBackend’

214
Q

dra: to make dra work

A

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
Q

django: To debug to False in heroku environment

A

heroku config:set ON_HEROKU=1

if ON_HEROKU in os.environ:
return False

216
Q

the benefit of using a with state (context manager), is

A

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
Q

to run a function on each line of a csv without loading into memory, type

A
with open("file.txt", "r") as file:
    for line in file:
        do_something_with(line.split(', '))
218
Q

python: map does not

A

run in place, must assign the return to a variable

219
Q

python: range(3) return

A

[0, 1, 2]

220
Q

python: To convert a list of intergers to strings, type

A

new_list = [str(item) for item in [1,2,3]]

or

new_list = map(lambda x: str(x), [1,2,3])

221
Q

python: To join a list of strings with a separator, type

A

’, ‘.join(my_list)

222
Q

python: 5 > None will return

A

True

223
Q

python: before writing every function

A

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
Q

django: to send a blob to django, type

A
@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
Q

FormData() is used

A

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
Q

@login_required does not work for

A

django rest framework style authentication

227
Q

drf: To send an authenticated request to drf on a function view

A
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
Q

django-storages: To save an image, type

A

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
Q

when setting up allauth, make sure

A

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
Q

drf: A drf auth token is valid for

A

forever

https://stackoverflow.com/questions/22943050/how-long-is-token-valid-django-rest-framework

231
Q

mac app:

A

To make a mac app distribution, your membership must be up to date

232
Q

to have nested objects inside a serializer

A

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