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.
What are the benefits of creating apps?
Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.
What is Django’s model philosophy?
A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive things from it.
This includes the migrations - unlike in Ruby On Rails, for example, migrations are entirely derived from your models file, and are essentially just a history that Django can roll through to update your database schema to match your current models.
What does the models.Model represent?
Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model. For example in:
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
Each field is represented by an instance of a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.
Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.
A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.
Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.
Once you’ve created your models in Django and have completed the migration process, what does django do?
Django is able to:
Create a database schema (CREATE TABLE statements) for the app.
Create a Python database-access API for accessing the objects.
Table names are automatically generated by combining the name of the app and the lowercase name of the model. (You can override this behavior.)
Primary keys (IDs) are added automatically.
By convention, Django appends “_id” to the foreign key field name.
It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key autoincrement (SQLite) are handled for you automatically. Same goes for the quoting of field names – e.g., using double quotes or single quotes.
What does python manage.py check do?
checks for any problems in your project without making migrations or touching the database.
How do you invoke Django’s free API?
To invoke the interactive Python shell, use this command:
$ python manage.py shell
What are regular expressions ?
Regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.
So we can say that the task of searching and extracting is so common that Python has a very powerful library called regular expressions that handles many of these tasks quite elegantly.
$ Matches the end of the line
\s Matches whitespace
\S Matches any non-whitespace character
* Repeats a character zero or more times
\S Matches any non-whitespace character
*? Repeats a character zero or more times (non-greedy)
+ Repeats a character one or more times
+? Repeats a character one or more times (non-greedy)
[aeiou] Matches a single character in the listed set
[^XYZ] Matches a single character not in the listed set
[a-z0-9] The set of characters can include a range
( Indicates where string extraction is to start
) Indicates where string extraction is to end
How do you use the regular expression library in django?
# Importing module required for regular # expressions import re
# Example string s = 'Hello from shubhamg199630@gmail.com to priya@yahoo.com about the meeting @2PM'
# \S matches any non-whitespace character # @ for as in the Email # + for Repeats a character one or more times lst = re.findall('\S+@\S+', s)
# Printing of List print(lst)
What are XSS attacks?
XSS attacks allow a user to inject client side scripts into the browsers of other users. This is usually achieved by storing the malicious scripts in the database where it will be retrieved and displayed to other users, or by getting users to click a link which will cause the attacker’s JavaScript to be executed by the user’s browser. However, XSS attacks can originate from any untrusted source of data, such as cookies or Web services, whenever the data is not sufficiently sanitized before including in a page.
What are CSRF attacks?
CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent.
What are SQL injection attacks?
SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. This can result in records being deleted or data leakage.
What are clickjacking attacks?
Clickjacking is a type of attack where a malicious site wraps another site in a frame. This attack can result in an unsuspecting user being tricked into performing unintended actions on the target site.
Each model in Django is what?
A Python class that subclasses django.db.models.Model