Django Flashcards

1
Q

what is settings.py?

A

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.

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

what is urls.py?

A

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

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

what is wsgi.py?

A

used to help your Django application communicate with the web server. You can treat this as boilerplate.

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

what is manage.py?

A

script is used to create applications, work with databases, and start the development web server.

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

what is the migration folder for?

A

used to store “migrations” — files that allow you to automatically update your database as you modify your models.

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

what is __init__.py for?

A

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.

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

what is makemigrations for?

A

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

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

what is the migrate command for?

A

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.

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

What is the csrf token?

A

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

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

What are ORMs?

A

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

How do you use the django shell environment?

A

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

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

What is request.POST?

A

Data from POST request

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

What is request.GET?

A

Data from GET request

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

What is request.method?

A

Returns the method/HTTP verb associated with the request

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

What are sessions?

A

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

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

Your controller file in django is:

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

GET and POST are the only HTTP methods to use when dealing with forms. What are they and how are they used?

A

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.

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

When using the runserver command, the default port is 8000 on the internal IP. What can you do to change the server’s port?

A

pass it as a command-line argument. For instance, this command starts the server on port 8080:

$ python manage.py runserver 8080

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

What does the path() function do?

A

path() is passed four arguments, two required: route and view, and two optional: kwargs, and name.

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

What is the route argument in path for?

A

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/

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

What is the view function in urlconf or an apps urls.py?

A

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.

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

What is the kwargs argument in path for?

A

Arbitrary keyword arguments can be passed in a dictionary to the target view.

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

What is the name argument in path for?

A

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

How do you setup the database in django’s settings.py module?

A

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.

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

What are the benefits of creating apps?

A

Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.

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

What is Django’s model philosophy?

A

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.

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

What does the models.Model represent?

A

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.

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

Once you’ve created your models in Django and have completed the migration process, what does django do?

A

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.

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

What does python manage.py check do?

A

checks for any problems in your project without making migrations or touching the database.

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

How do you invoke Django’s free API?

A

To invoke the interactive Python shell, use this command:

$ python manage.py shell

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

What are regular expressions ?

A

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

How do you use the regular expression library in django?

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

What are XSS attacks?

A

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.

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

What are CSRF attacks?

A

CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent.

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

What are SQL injection attacks?

A

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.

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

What are clickjacking attacks?

A

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.

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

Each model in Django is what?

A

A Python class that subclasses django.db.models.Model

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

Each attribute of the model represents what?

A

A database field

39
Q

What application does Django offer to make queries?

A

An automatically generated database access API

40
Q

What is the most important and the only required part of a model?

A

The list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete.

41
Q

Each field in your model is what?

A

An instance of the appropriate Field class.

42
Q

Django uses the field class types to determine a few things: What are they?

A
  1. The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT).
  2. The default HTML widget to use when rendering a form field (e.g. , ).
  3. The minimal validation requirements, used in Django’s admin and in automatically-generated forms.
43
Q

How do you access a model with choices field in ORM?

A

using the display() method
rom django.db import models

class Person(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=60)
    "shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
'L'
>>> p.get_shirt_size_display()
'Large'
44
Q

What are verbose field names?

A

Each field type, except for ForeignKey, ManyToManyField and OneToOneField, takes an optional first positional argument – a verbose name. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.

In this example, the verbose name is “person’s first name”:

first_name = models.CharField(“person’s first name”, max_length=30)

45
Q

Which fields require the first argument to be a model class?

A

ForeignKey, ManyToManyField and OneToOneField require the first argument to be a model class, so use the verbose_name keyword argument:

poll = models.ForeignKey(
    Poll,
    on_delete=models.CASCADE,
    verbose_name="the related poll",
)
sites = models.ManyToManyField(Site, verbose_name="list of sites")
place = models.OneToOneField(
    Place,
    on_delete=models.CASCADE,
    verbose_name="related place",
)
The convention is not to capitalize the first letter of the verbose_name. Django will automatically capitalize the first letter where it needs to.

The convention is not to capitalize the first letter of the verbose_name. Django will automatically capitalize the first letter where it needs to.

46
Q

What are the three most common types of database relationships:

A

many-to-one, many-to-many and one-to-one.

47
Q

What are many-to-one relationships?

A

To define a many-to-one relationship, use django.db.models.ForeignKey. You use it just like any other Field type: by including it as a class attribute of your model.

ForeignKey requires a positional argument: the class to which the model is related.

For example, if a Car model has a Manufacturer – that is, a Manufacturer makes multiple cars but each Car only has one Manufacturer – use the following definitions:

from django.db import models

class Manufacturer(models.Model):
    # ...
    pass
class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    # ...
You can also create recursive relationships (an object with a many-to-one relationship to itself) and relationships to models not yet defined; see the model field reference for details.

It’s suggested, but not required, that the name of a ForeignKey field (manufacturer in the example above) be the name of the model, lowercase. You can, of course, call the field whatever you want. For example:

class Car(models.Model):
    company_that_makes_it = models.ForeignKey(
        Manufacturer,
        on_delete=models.CASCADE,
    )
    # ...
48
Q

What are many-to-many relationships?

A

To define a many-to-many relationship, use ManyToManyField. You use it just like any other Field type: by including it as a class attribute of your model.

ManyToManyField requires a positional argument: the class to which the model is related.

For example, if a Pizza has multiple Topping objects – that is, a Topping can be on multiple pizzas and each Pizza has multiple toppings – here’s how you’d represent that:

from django.db import models

class Topping(models.Model):
    # ...
    pass
class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)
As with ForeignKey, you can also create recursive relationships (an object with a many-to-many relationship to itself) and relationships to models not yet defined.

It’s suggested, but not required, that the name of a ManyToManyField (toppings in the example above) be a plural describing the set of related model objects.

It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models – not both.

Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (rather than Topping having a pizzas ManyToManyField ) because it’s more natural to think about a pizza having toppings than a topping being on multiple pizzas. The way it’s set up above, the Pizza form would let users select the toppings.

See also

See the Many-to-many relationship model example for a full example.

ManyToManyField fields also accept a number of extra arguments which are explained in the model field reference. These options help define how the relationship should work; all are optional.

49
Q

What are meta options?

A

Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.

A complete list of all possible Meta options can be found in the model option reference.

Give your model metadata by using an inner class Meta, like so:

from django.db import models

class Ox(models.Model):
    horn_length = models.IntegerField()
    class Meta:
        ordering = ["horn_length"]
        verbose_name_plural = "oxen"
50
Q

What is the most important attribute of a model?

A

The Manager. It’s the interface through which database query operations are provided to Django models and is used to retrieve the instances from the database. If no custom Manager is defined, the default name is objects. Managers are only accessible via model classes, not the model instances.

51
Q

What are methods intended for?

A

Define custom methods on a model to add custom “row-level” functionality to your objects. Whereas Manager methods are intended to do “table-wide” things, model methods should act on a particular model instance.

This is a valuable technique for keeping business logic in one place – the model.

For example, this model has a few custom methods:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()
def baby_boomer_status(self):
    "Returns the person's baby-boomer status."
    import datetime
    if self.birth_date < datetime.date(1945, 8, 1):
        return "Pre-boomer"
    elif self.birth_date < datetime.date(1965, 1, 1):
        return "Baby boomer"
    else:
        return "Post-boomer"

@property
def full_name(self):
    "Returns the person's full name."
    return '%s %s' % (self.first_name, self.last_name) The last method in this example is a property.

The model instance reference has a complete list of methods automatically given to each model.

52
Q

What is the __str__() method for?

A

A Python “magic method” that returns a string representation of any object. This is what Python and Django will use whenever a model instance needs to be coerced and displayed as a plain string. Most notably, this happens when you display an object in an interactive console or in the admin.

You’ll always want to define this method; the default isn’t very helpful at all.

53
Q

What is the __str__() method for?

A

This tells Django how to calculate the URL for an object. Django uses this in its admin interface, and any time it needs to figure out a URL for an object.

Any object that has a URL that uniquely identifies it should define this method.

54
Q

What is the super().save(*args, **kwargs) method?

A

It ensures that the object still gets saved into the database. If you forget to call the superclass method, the default behavior won’t happen and the database won’t get touched.

55
Q

What are abstract base classes?

A

Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

An example:

from django.db import models

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    class Meta:
        abstract = True
class Student(CommonInfo):
    home_group = models.CharField(max_length=5)
The Student model will have three fields: name, age and home_group. The CommonInfo model cannot be used as a normal Django model, since it is an abstract base class. It does not generate a database table or have a manager, and cannot be instantiated or saved directly.

Fields inherited from abstract base classes can be overridden with another field or value, or be removed with None.

For many uses, this type of model inheritance will be exactly what you want. It provides a way to factor out common information at the Python level, while still only creating one database table per child model at the database level.

56
Q

Why should you be careful with related_name and related_query_name?

A

If you are using related_name or related_query_name on a ForeignKey or ManyToManyField, you must always specify a unique reverse name and query name for the field. This would normally cause a problem in abstract base classes, since the fields on this class are included into each of the child classes, with exactly the same values for the attributes (including related_name and related_query_name) each time.

To work around this problem, when you are using related_name or related_query_name in an abstract base class (only), part of the value should contain ‘%(app_label)s’ and ‘%(class)s’.

'%(class)s' is replaced by the lower-cased name of the child class that the field is used in.
'%(app_label)s' is replaced by the lower-cased name of the app the child class is contained within. Each installed application name must be unique and the model class names within each app must also be unique, therefore the resulting name will end up being different.
For example, given an app common/models.py:

from django.db import models

class Base(models.Model):
    m2m = models.ManyToManyField(
        OtherModel,
        related_name="%(app_label)s_%(class)s_related",
        related_query_name="%(app_label)s_%(class)ss",
    )
    class Meta:
        abstract = True
class ChildA(Base):
    pass
class ChildB(Base):
    pass

The reverse name of the common.ChildA.m2m field will be common_childa_related and the reverse query name will be common_childas. The reverse name of the common.ChildB.m2m field will be common_childb_related and the reverse query name will be common_childbs. Finally, the reverse name of the rare.ChildB.m2m field will be rare_childb_related and the reverse query name will be rare_childbs. It’s up to you how you use the ‘%(class)s’ and ‘%(app_label)s’ portion to construct your related name or related query name but if you forget to use it, Django will raise errors when you perform system checks (or run migrate).

If you don’t specify a related_name attribute for a field in an abstract base class, the default reverse name will be the name of the child class followed by ‘_set’, just as it normally would be if you’d declared the field directly on the child class. For example, in the above code, if the related_name attribute was omitted, the reverse name for the m2m field would be childa_set in the ChildA case and childb_set for the ChildB field.

57
Q

What is multi-table inheritance?

A

The second type of model inheritance supported by Django is when each model in the hierarchy is a model all by itself. Each model corresponds to its own database table and can be queried and created individually. The inheritance relationship introduces links between the child model and each of its parents (via an automatically-created OneToOneField). For example:

from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)
class Restaurant(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)
All of the fields of Place will also be available in Restaurant, although the data will reside in a different database table. So these are both possible:

> > > Place.objects.filter(name=”Bob’s Cafe”)
Restaurant.objects.filter(name=”Bob’s Cafe”)
If you have a Place that is also a Restaurant, you can get from the Place object to the Restaurant object by using the lower-case version of the model name:

>>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
>>> p.restaurant

However, if p in the above example was not a Restaurant (it had been created directly as a Place object or was the parent of some other class), referring to p.restaurant would raise a Restaurant.DoesNotExist exception.

The automatically-created OneToOneField on Restaurant that links it to Place looks like this:

place_ptr = models.OneToOneField(
    Place, on_delete=models.CASCADE,
    parent_link=True,
)
You can override that field by declaring your own OneToOneField with parent_link=True on Restaurant.
58
Q

How do you combine meta and multi-table inheritance?

A

In the multi-table inheritance situation, it doesn’t make sense for a child class to inherit from its parent’s Meta class. All the Meta options have already been applied to the parent class and applying them again would normally only lead to contradictory behavior (this is in contrast with the abstract base class case, where the base class doesn’t exist in its own right).

So a child model does not have access to its parent’s Meta class. However, there are a few limited cases where the child inherits behavior from the parent: if the child does not specify an ordering attribute or a get_latest_by attribute, it will inherit these from its parent.

If the parent has an ordering and you don’t want the child to have any natural ordering, you can explicitly disable it:

class ChildModel(ParentModel):
    # ...
    class Meta:
        # Remove parent's ordering effect
        ordering = []
59
Q

What does Field name “hiding” is not permitted mean?

A

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields. If a non-abstract model base class has a field called author, you can’t create another model field or define an attribute called author in any class that inherits from that base class.

This restriction doesn’t apply to model fields inherited from an abstract model. Such fields may be overridden with another field or value, or be removed by setting field_name = None.

Overriding fields in a parent model leads to difficulties in areas such as initializing new instances (specifying which field is being initialized in Model.__init__) and serialization. These are features which normal Python class inheritance doesn’t have to deal with in quite the same way, so the difference between Django model inheritance and Python class inheritance isn’t arbitrary.

This restriction only applies to attributes which are Field instances. Normal Python attributes can be overridden if you wish. It also only applies to the name of the attribute as Python sees it: if you are manually specifying the database column name, you can have the same column name appearing in both a child and an ancestor model for multi-table inheritance (they are columns in two different database tables).

Django will raise a FieldError if you override any model field in any ancestor model.

60
Q

How can you organize models in a package?

A

The manage.py startapp command creates an application structure that includes a models.py file. If you have many models, organizing them in separate files may be useful.

To do so, create a models package. Remove models.py and create a myapp/models/ directory with an __init__.py file and the files to store your models. You must import the models in the __init__.py file.

For example, if you had organic.py and synthetic.py in the models directory:

myapp/models/__init__.py
from .organic import Person
from .synthetic import Robot
Explicitly importing each model rather than using from .models import * has the advantages of not cluttering the namespace, making code more readable, and keeping code analysis tools useful.

61
Q

How does Django perform database aggregation?

A

Let’s refer to the following models. These models are used to track the inventory for a series of online bookstores:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
class Publisher(models.Model):
    name = models.CharField(max_length=300)
    num_awards = models.IntegerField()
class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    pubdate = models.DateField()
class Store(models.Model):
    name = models.CharField(max_length=300)
    books = models.ManyToManyField(Book)
    registered_users = models.PositiveIntegerField()
Here’s how to do common aggregate queries, assuming the models above:

Total number of books.
»> Book.objects.count()
2452

# Total number of books with publisher=BaloneyPress
>>> Book.objects.filter(publisher\_\_name='BaloneyPress').count()
73
# Average price across all books.
>>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
{'price\_\_avg': 34.35}
# Max price across all books.
>>> from django.db.models import Max
>>> Book.objects.all().aggregate(Max('price'))
{'price\_\_max': Decimal('81.20')}
# Difference between the highest priced book and the average price of all books.
>>> from django.db.models import FloatField
>>> Book.objects.aggregate(
...     price_diff=Max('price', output_field=FloatField()) - Avg('price'))
{'price_diff': 46.85}
# All the following queries involve traversing the BookPublisher
# foreign key relationship backwards.

Each publisher, each with a count of books as a “num_books” attribute.
»> from django.db.models import Count
»> pubs = Publisher.objects.annotate(num_books=Count(‘book’))
»> pubs
, , …]>
»> pubs[0].num_books
73

Each publisher, with a separate count of books with a rating above and below 5
»> from django.db.models import Q
»> above_5 = Count(‘book’, filter=Q(book__rating__gt=5))
»> below_5 = Count(‘book’, filter=Q(book__rating__lte=5))
»> pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
»> pubs[0].above_5
23
»> pubs[0].below_5
12

The top 5 publishers, in order by number of books.
»> pubs = Publisher.objects.annotate(num_books=Count(‘book’)).order_by(‘-num_books’)[:5]
»> pubs[0].num_books
1323

62
Q

How does django generate aggregates over a QuerySet

A

Django provides two ways to generate aggregates. The first way is to generate summary values over an entire QuerySet. For example, say you wanted to calculate the average price of all books available for sale. Django’s query syntax provides a means for describing the set of all books:

> > > Book.objects.all()
What we need is a way to calculate summary values over the objects that belong to this QuerySet. This is done by appending an aggregate() clause onto the QuerySet:

>>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
{'price\_\_avg': 34.35}
The all() is redundant in this example, so this could be simplified to:

> > > Book.objects.aggregate(Avg(‘price’))
{‘price__avg’: 34.35}
The argument to the aggregate() clause describes the aggregate value that we want to compute - in this case, the average of the price field on the Book model. A list of the aggregate functions that are available can be found in the QuerySet reference.

aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. The name is an identifier for the aggregate value; the value is the computed aggregate. The name is automatically generated from the name of the field and the aggregate function. If you want to manually specify a name for the aggregate value, you can do so by providing that name when you specify the aggregate clause:

> > > Book.objects.aggregate(average_price=Avg(‘price’))
{‘average_price’: 34.35}
If you want to generate more than one aggregate, you just add another argument to the aggregate() clause. So, if we also wanted to know the maximum and minimum price of all books, we would issue the query:

> > > from django.db.models import Avg, Max, Min
Book.objects.aggregate(Avg(‘price’), Max(‘price’), Min(‘price’))
{‘price__avg’: 34.35, ‘price__max’: Decimal(‘81.20’), ‘price__min’: Decimal(‘12.99’)}

63
Q

What is the atomic method in django?

A

Django provides a single API to control database transactions.

atomic(using=None, savepoint=True)[source]¶
Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point.

atomic is usable both as a decorator:

from django.db import transaction

@transaction.atomic
def viewfunc(request):
    # This code executes inside a transaction.
    do_stuff()
and as a context manager:
64
Q

What are view functions in django?

A

A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.

A simple view¶
Here’s a view that returns the current date and time, as an HTML document:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "It is now %s." % now
    return HttpResponse(html)
Let’s step through this code one line at a time:

First, we import the class HttpResponse from the django.http module, along with Python’s datetime library.

Next, we define a function called current_datetime. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request.

Note that the name of the view function doesn’t matter; it doesn’t have to be named in a certain way in order for Django to recognize it. We’re calling it current_datetime here, because that name clearly indicates what it does.

The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object. (There are exceptions, but we’ll get to those later.)

So, to recap, this view function returns an HTML page that includes the current date and time. To display this view at a particular URL, you’ll need to create a URLconf;

65
Q

What are regular expressions?

A

Regular expressions, commonly known as regex, are a set of rules for identifying or matching strings. Many programming languages, including Python, support use of regular expressions for matching and searching strings.

regex is any valid python regex that has to be processed. This would be absolute in the project urls.py and relative to the mount point in an app’s urls.py

Common uses include searching string inputs from users. Search engines and other form input, like user registration and login, are great examples of correct uses for regular expressions. As you’ve seen, Django uses regex to match url patterns in routing.

66
Q

What is django?

A

Django is a framework for full stack web development.
A project in django is analogous to a website. Once we have a project ready, we can host it using any wsgi supported server.

67
Q

What is django-admin.py?

A

The admin interface is itself a django app.
It is a contrib app, which means it is a community contributed app. It is flexible enough to accommodate any other app’s models and have admin actions for them.
Note that the admin app uses a urls.py to keep its urls separate from the project. In addition to the startproject subcommand, it also includes a lot of helper subcommands that can be useful while maintaining a django project.

68
Q

How do you access the development server?

A

You can quickly checkout the development server at this point by running:

python manage.py runserver

69
Q

What is the CharField, TextField and DateField in a model?

A

Each CharField requires a max_length argument which specifies the maximum length of the characters that the field can hold.
A TextField can contain any number of characters and is suitable for fields such as description, summary, content etc.
To make the description field optional, we pass the null and blank arguments as True
DateField holds a date. If you need to store the time too, use DateTimeField instead.

70
Q

What is unicode and how does Django use it?

A

Unicode is a computing industry standard for the consistent encoding, representation, and handling of text expressed in most of the world’s writing systems.

Django uses a models __unicode__ property to display the the table’s column labels

71
Q

What are some of the features of the admin.py app?

A

Django used our model field types (CharField, TextField, DateField) to create HTML widgets in the admin page
Genre Field has a drop down field with the CHOICES attributes used to populate its key, value pairs
DateField includes a handy calendar popup
Description is optional, so it is not highlighted like the rest of the fields
Django provides automatic form validation. Try entering blank values, or wrong dates and submitting the form
In accordance with the DRY principle, models.py is the only place where you specified the fields.

72
Q

how do you access the database shell? And what is it for?

A

python manage.py dbshell

‘dbshell’ is a handy manage.py subcommand that will give you access to the database using your DATABASES settings You can check the tables in the database by typing the following in the shell:
.tables —for sqlite
show tables —-for mysql
\dt —-for pgsql

73
Q

What is urlConf?

A

URL configuration - entry points located in main project folder as urls.py.
This controls our website’s points of entry. All incoming urls will be matched with the regexes in the urlpatterns and the view corresponding to the first match will get to handle the request. A request url that does not match any urlconf entry will be 404’ed.

A typical urlconf entry looks like this:
(r’’, , ),

regex is any valid python regex that has to be processed. This would be absolute in the project urls.py and relative to the mount point in an app’s urls.py

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. More about views later.

arg_dict is an optional dict of arguments that will be passed to the view_function. In addition, options can be declared from the url regex too. For example:

path(‘object//’, views.get_object)
will match all urls having an integer after object/. Also, the value will be passed as object_id to the get_object function.

74
Q

What are named urls?

A

Usually, we would want an easier way to remember the urls so that we could refer them in views or templates. We could name our urls by using the path constructor. For example:

path(r’^welcome/$’, ‘app.views.welcome’, name=’welcome’),
This line is similar to the previous urls, but we have an option of passing a name argument.

To get back the url from its name, django provides:

django.url.reverse function for use in views
url templatetag for use in templates

75
Q

What is a django template?

A

A template is a structure of webpage that will be rendered using a context and returned as response if you want it to. A django.template.Template object can be rendered using the render method.

Normally templates are html files with some extra django content, such as templatetags and variables. Note that our templates need not be publicly accessible(in fact they shouldn’t be) from a webserver. They are not meant to be displayed directly; django will process them based on the request, context etc and respond with the rendered templates.

76
Q

What is a context?

A

A context is a dict that will be used to render a page from a template. All context keys are valid template variables.

To display a user name in your template, suppose you provide the username in your context, you could do:

Hello {{ username }}
When this template is rendered using (e.g. using render), username will be replaced with its value

You can pass any variable to the context, so you can call a dict’s key, or an objects property. However you cannot pass any arguments to the property.

For example:

Hello {{ user.username }}
can be used to get user[‘username’] or user.username

Similarly:

<a>{{ user.username }}</a>
can be used to get user.get_absolute_url()

77
Q

What are template tags?

A

Templatetags are helpers to the template. Jinja2 is an example. Suppose you have an iterable with a list of objects in your context:

{% for object in objects %}
{{ object }}
{% endfor %}

would render them. If this is a html template, we would prefer:

{% if objects %}
<ul>
    {% for object in objects %}
        <li>
            {{ object }}
        </li>
    {% endfor %}
</ul>
{% endif %}
which would render the objects in html unordered list.

Note that {% if %} {% for %} {% endif %} {% endfor %} are all built-in templatetags. If and for behave very much like their python counterparts.

78
Q

What are common template tags and template inheritance?

A

Some templatetags we will use in our application:

url
This templatetag takes a named url or view function and renders the url as found by reverse

For example:
<a>View All</a>
would output

<a>View All</a>
It also takes arguments:

<a>{{ paste }}</a>
would output

<a>Sample Paste</a>

You must make sure the correct urlconf entry for the give url exists. If the url entry does not exist, or the number of arguments does not match, this templatetag will raise a NoReverseMatch exception.

csrf_token

This is a security related tag used in forms to prevent cross site request forgery.

include

This will simply include any file that can be found by the TEMPLATE_LOADERS where it is called

extends

This will extend another template and provides template inheritance. You can have a base template and have other specific template extend the base template.

block and endblock

blocks are used to customize the base page from a child page. If the base page defines a block called
head, the child page can override that block with its own contents.

load

This is used to load custom templatetags. More about writing and using custom templatetags later.

79
Q

What are filters?

A

Filters are simple functions which operate on a template variable and manipulate them.

For example in our previous template:

Hello {{ username|capfirst }}
Here capfirst is a filter that will capitalize the first char our username

80
Q

What’s a critical point to remember about templates?

A

Templates are not meant for programming:
One of the core django philosophy is that templates are meant for rendering the context and optionally making a few aesthetic changes only. Templates should not be used for handling complex queries or operations. This is also useful to keep the programming and designing aspects of the website separate. Template language should be easy enough to be written by designers.

81
Q

What are generic views?

A

Django’s generic views were developed to ease that pain.They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.

Extending Generic Views
There’s no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations.

This is one of the reasons generic views were redesigned for the 1.3 release - previously, they were just view functions with a bewildering array of options; now, rather than passing in a large amount of configuration in the URLconf, the recommended way to extend generic views is to subclass them, and override their attributes or methods.

82
Q

What are django Forms?

A

Forms can be autogenerated by django’s forms library.
to display the form, all you have to do is render the form variable
form has a method as_table that will render it as table, other options are as_p, as_ul for enclosing the form in <p> and </p><ul> 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 </ul>

83
Q

How is the generic view created?

A

The generic view displays the details about the object with a given id. Note that:
Using DetailView as an example:

model and template_name are the arguments passed to DetailView. (ProjectDetailView)
we are naming this view using the url constructor and passing the name argument:
urlpatterns = [
path(‘paste/’, PasteDetail.as_view(), name=’pastebin_paste_detail’),
]

This name can be referred to from views or templates and helps in keeping this DRY.
the DetailView view will render the pastebin/paste_detail.html template.

84
Q

What is django’s pk property?

A

Regardless of whether you define a primary key field yourself, or let Django supply one for you, each model will have a property called pk. It behaves like a normal attribute on the model, but is actually an alias for whichever attribute is the primary key field for the model. You can read and set this value, just as you would for any other attribute, and it will update the correct field in the model.

85
Q

What does this object do?

form = PostForm(request.POST or None)

A

Here we are handling GET and POST in the same view. If this is a GET request, the form would be empty else it would be filled with the POST contents.

86
Q

What does form.is_valid do?

A

validates the form and returns True or False

87
Q

How can you restrict class based views to a condition?

A

To restrict views to a condition, we can use the user_passes_test decorator from contrib.auth. The decorator takes a callable which should perform the test on the user argument and return True or False. The view is called only when the user passes the test. If the user is not logged in or does not pass the test, it redirects to LOGIN_URL of settings. By default this is /accounts/login and we will handle this url from urls.py

88
Q

Give two useful examples of built-in django decorators.

A

django.contrib.admin.views.decorators import staff_member_required
Restricts view to staff members only.

django.contrib.auth.decorators.login_required
Restricts view to logged in users only

89
Q

What are RSS feeds?

A

Short for Really Simple Syndication or Rich Site Summary, RSS revolutionized the way that users interact with content online.

Instead of checking back every day to any particular site to see if it’s been updated, RSS feeds give users the ability to simply subscribe to the RSS feed, much like you would subscribe to a newspaper, and then read the updates from the site, delivered via RSS feeds, in what’s called a “feed reader.”

RSS feeds benefit those who actually own or publish a website as well since site owners can get their updated content to subscribers much more quickly by submitting feeds to various XML and RSS directories.

RSS feeds are simple text files that, once submitted to feed directories, will allow subscribers to see content within a very short time after it’s updated.

This content can be aggregated to be viewed even more easily by using a feed reader. A feed reader, or feed aggregator, is just a really simple way to view all your feeds at one time via one interface.

90
Q

What is the difference between REST and CRUD?

A

REST refers to a set of defining principles for developing API. It uses HTTP protocols like GET, PUT, POST to link resources to actions within a client-server relationship. In addition to the client-server mandate, it has several other defining constraints. The principles of RESTful architecture serve to create a stable and reliable application, that offers simplicity and end-user satisfaction.

CRUD is an acronym for CREATE, READ, UPDATE, DELETE. These form the standard database commands that are the foundation of CRUD. By definition, CRUD is more of a cycle than an architectural system. On any dynamic website, there are likely multiple CRUD cycles that exist.

What’s the Difference?
CRUD is a cycle that can be mapped to REST, by design. Permanence, as defined in the context of CRUD, is a smart way for applications to mitigate operational commands between clients and services.

But REST governs much more than permanence within its principles of architecture. Here are some of the ways that REST is not only different than CRUD but also offers much more.

REST is an architectural system centered around resources and hypermedia, via HTTP protocols
CRUD is a cycle meant for maintaining permanent records in a database setting
CRUD principles are mapped to REST commands to comply with the goals of RESTful architecture
In REST:

Representations must be uniform with regard to resources
Hypermedia represents relationships between resources
Only one entry into an API to create one self-contained interface, then hyperlink to create relationships.

91
Q

What is the form.initial attribute?

A

The form.initial attribute is a dict that holds initial data of the form. A session lasts until the user logs out or clears the cookies (e.g. by closing the browser). django identifies the session using sessionid cookie.

92
Q

What is the default session backend in django?

A

The default session backend is django.contrib.sessions.backends.db i.e. database backend, but it can be configured to file or cache backend as well.

93
Q

What are the benefits of using class based views?

A

Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:

Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.

EXAMPLE:
from django.http import HttpResponse
// Function Based View.
def my_view(request):
    if request.method == 'GET':
        # 
        return HttpResponse('result')
from django.http import HttpResponse
from django.views import View
// Class Based View
class MyView(View):
    def get(self, request):
        # 
        return HttpResponse('result')
94
Q

What does it mean to produce hash values?

A

Producing hash values for accessing data or for security. A hash value (or simply hash), also called a message digest, is a number generated from a string of text. … The recipient then decrypts both the message and the hash, produces another hash from the received message, and compares the two hashes.