Django Flashcards
what is settings.py?
settings.py is a list of project wide settings with some default values. You will need to edit this often when installing new django applications, deployment etc. This is where we register any applications we create, the location of our static files, database configuration details, etc.
what is urls.py?
defines the site url-to-view mappings. While this could contain all the url mapping code, it is more common to delegate some of the mapping to particular applications
what is wsgi.py?
used to help your Django application communicate with the web server. You can treat this as boilerplate.
what is manage.py?
script is used to create applications, work with databases, and start the development web server.
what is the migration folder for?
used to store “migrations” — files that allow you to automatically update your database as you modify your models.
what is __init__.py for?
an empty file created here so that Django/Python will recognise the folder as a Python Package and allow you to use its objects within other parts of the project.
what is makemigrations for?
command creates (but does not apply) the migrations for all applications installed in your project (you can specify the application name as well to just run a migration for a single project). This gives you a chance to checkout the code for these migrations before they are applied
what is the migrate command for?
takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.
Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data.
What is the csrf token?
CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent.
Django has built-in protection against most types of CSRF attacks, providing you have enabled and used it where appropriate. However, as with any mitigation technique, there are limitations.
For example, it is possible to disable the CSRF module globally or for particular views. You should only do this if you know what you are doing. There are other limitations if your site has subdomains that are outside of your control.
CSRF protection works by checking for a nonce in each POST request. This ensures that a malicious user cannot simply replay a form POST to your Web site and have another logged in user unwittingly submit that form. The malicious user would have to know the nonce, which is user specific (using a cookie).
What are ORMs?
ORMs are used to create a language-specific object oriented representation of a table. When tables are objects, attributes of these objects represent the columns in the database, while methods will correspond to common queries.
The reason that ORMs are useful is so that we can write pure Python code without having to manage long SQL query strings in our logic. You know from experience how ugly SQL queries can get when doing complex selects. Given clearly named table methods our code becomes much more clear and easy to read with the help of an ORM.
How do you use the django shell environment?
go to command line and access the apps model by typing in from apps.social.models import *
ORM Commands
Now that you have imported your models, you can use the model object to insert, delete, and modify records in your models. For example,
Creating a new record
Blog.objects.create({{field1}}=”{{value}}”, {{field2}}=”{{value}}”, etc) # creates a new record in the Blog table
Blog.objects.create(name=”Star Wars Blog”, desc=”Everything about Star Wars”) # creates a new blog record
Blog.objects.create(name=”CodingDojo Blog”) # creates a new blog record with the empty desc field
Alternative way of creating a record
b = Blog(name=”Disney Blog”, desc=”Disney stuff”)
b.name = “Disney Blog!”
b.desc = “Disney stuff!!!”
b.save()
Basic Retrieval
Blog.objects.first() - retrieves the first record in the Blog table
Blog.objects.last() - retrieves the last record in the Blog table
Blog.objects.all() - retrieves all records in the Blog table
Blog.objects.count() - shows how many records are in the Blog table
Displaying records
Blog.objects.first().__dict__ - shows all the values of a single record/object as a dictionary
Blog.objects.all().values() - as shown in the videos, shows all the values of a QuerySet (QuerySet contains multiple records)
Updating the record - once you obtain an object that has the record you want to modify, use save() to update the record. For example
b = Blog.objects.first() # gets the first record in the blogs table
b.name = “CodingDojo Blog” # set name to be “CodingDojo Blog”
b.save() # updates the blog record
Deleting the record - use delete(). For example
b = Blog.objects.get(id=1)
b.delete() # deletes that particular record
Other methods to retrieve records
Blog.objects.get(id=1) - retrieves where id is 1; get() retrieves one and only one record. It will return an error if it finds fewer than or more than one match.
Blog.objects.filter(name=”mike”) - retrieves records where name is “mike”; returns multiple records
Blog.objects.exclude(name=”mike”) - opposite of filter; returns multiple records
Blog.objects.order_by(“created_at”) - orders by created_date field
Blog.objects.order_by(“-created_at”) - reverses the order
Blog.objects.raw(“SELECT * FROM {{app_name}}_{{class/table name}}”) - performs a raw SQL query
Blog.objects.first().comments.all() - grabs all comments from the first Blog
Blog.objects.get(id=15).comments.first() - grabs the first comment from Blog id = 15
Comment.objects.get(id=15).blog.name - returns the name of the blog where Comment id = 15 belongs to
Setting Relationship
Comment.objects.create(blog=Blog.objects.get(id=1), comment=”test”) - create a new comment where the comment’s blog points to Blog.objects.get(id=1).
What is request.POST?
Data from POST request
What is request.GET?
Data from GET request
What is request.method?
Returns the method/HTTP verb associated with the request
What are sessions?
Sessions are the mechanism used by Django (and most of the Internet) for keeping track of the “state” between the site and a particular browser. Sessions allow you to store arbitrary data per browser, and have this data available to the site whenever the browser connects. Individual data items associated with the session are then referenced by a “key”, which is used both to store and retrieve the data.
Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users). You can configure Django to store the session data in other places (cache, files, “secure” cookies), but the default location is a good and relatively secure option.
Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself
Your controller file in django is:
The views.py file. This is where you create your methods such as def Index(request): return render(request, 'appname/page.html', context)
views.py has all the ‘action’ of our website. This is similar to the Controller of MVC architecture.
Views are just functions which take the HttpRequest object, and some optional arguments, then do some work and return a HttpResponse page. Use HttpResponseRedirect to redirect to some other url or HttpResponseForbidden to return a 403 Forbidden response.
By convention, all of an app’s views would be written in /views.py
A simple example to return “Hello World!” string response:
from django.http import HttpResponse
def hello_world(request): return HttpResponse("Hello World!") To render a template to response one would do:
from django.http import HttpResponse
from django.template import loader
def hello_world(request): template = loader.get_template("hello_world.html") context = {"username": "Monty Python"} return HttpResponse(template.render(context)) But there’s a simpler way:
from django.shortcuts import renders
def hello_world(request): return render(request,"hello_world.html", {"username": "Monty Python"})
GET and POST are the only HTTP methods to use when dealing with forms. What are they and how are they used?
Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response.
GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL. The URL contains the address where the data must be sent, as well as the data keys and values. You can see this in action if you do a search in the Django documentation, which will produce a URL of the form https://docs.djangoproject.com/search/?q=forms&release=1.
Any request that could be used to change the state of the system - for example, a request that makes changes in the database - should use POST. GET should be used only for requests that do not affect the state of the system.
GET would also be unsuitable for a password form, because the password would appear in the URL, and thus, also in browser history and server logs, all in plain text. Neither would it be suitable for large quantities of data, or for binary data, such as an image. A Web application that uses GET requests for admin forms is a security risk: it can be easy for an attacker to mimic a form’s request to gain access to sensitive parts of the system. POST, coupled with other protections like Django’s CSRF protection offers more control over access.
On the other hand, GET is suitable for things like a web search form, because the URLs that represent a GET request can easily be bookmarked, shared, or resubmitted.
When using the runserver command, the default port is 8000 on the internal IP. What can you do to change the server’s port?
pass it as a command-line argument. For instance, this command starts the server on port 8080:
$ python manage.py runserver 8080
What does the path() function do?
path() is passed four arguments, two required: route and view, and two optional: kwargs, and name.
What is the route argument in path for?
is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.
Patterns don’t search GET and POST parameters, or the domain name. For example, in a request to https://www.example.com/myapp/, the URLconf will look for myapp/. In a request to https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/
What is the view function in urlconf or an apps urls.py?
When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. view_function is a function that corresponds to this url. The function must return a HttpResponse object. Usually, shortcuts such as render, are used though.
What is the kwargs argument in path for?
Arbitrary keyword arguments can be passed in a dictionary to the target view.
What is the name argument in path for?
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.
How do you setup the database in django’s settings.py module?
By default, the configuration uses SQLite
If you wish to use another database, install the appropriate database bindings and change the following keys in the DATABASES ‘default’ item to match your database connection settings:
ENGINE – Either ‘django.db.backends.sqlite3’, ‘django.db.backends.postgresql’, ‘django.db.backends.mysql’, or ‘django.db.backends.oracle’. Other backends are also available.
NAME – The name of your database. If you’re using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, os.path.join(BASE_DIR, ‘db.sqlite3’), will store the file in your project directory.
If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST must be added. For more details, see the reference documentation for DATABASES.
-
{% for object in objects %}
- {{ object }} {% endfor %}
and
- tags respectively
form does not output the form tags or the submit button, so we will have to write them down in the template
you need to include csrf_token tag in every form posted to a local view. Django uses this to prevent cross site request forgery
the generated form includes validation based on the model fields