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)