Django Flashcards

1
Q

structure of newly created project mysite

A
mysite/
   manage.py
   mysite/
      \_\_init\_\_.py
      settings.py
      urls.py
      wsgi.py

manage.py - command line utility to interact with your project
__init__.py - empty file that tell python treat mysite directory as Python module
settings.py This indicates settings and configuration for your project and contains initial default settings.
urls.py This is the place where your URL patterns
live. Each URL defined here is mapped to a view.
wsgi.py This is the configuration to run your project as a Web Server Gateway Interface (WSGI) application.

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

Start the development server by typing the following command from your project’s root folder:

A

python manage.py runserver

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

DEBUG in settings

A

is a boolean that turns the debug mode of the project on and off.

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

ALLOWED_HOSTS in settings

A

is not applied while debug mode is on, or when
the tests are run. Once you move your site to production and set DEBUG to False , you will have to add your domain/host to this setting in order to allow it to serve your Django site.

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

INSTALLED_APPS in settings

A

is a setting you will have to edit for all projects.
This setting tells Django which applications are active for this site. By default, Django includes the following
applications:
django.contrib.admin - An administration site
django.contrib.auth - An authentication framework
django.contrib.contenttypes - a framework for handling contenttypes
django.contrib.sessions - a session framework
django.contrib.messages - a messaging framework
django.contrib.staticfiles - a framework for managing static files

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

MIDDLEWARE in settings

A

is a list containing middleware to be executed

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

ROOT_URLCONF in settings

A
indicates the Python module where the root URL
patterns of your application are defined.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

DATABASES in settings

A

is a dictionary that contains the settings for all the
databases to be used in the project. There must always be a default database. The default configuration uses an SQLite3 database.

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

LANGUAGE_CODE in settings

A

defines the default language code for django site

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

USE_TZ in settings

A

Django to activate/deactivate timezone support.
Django comes with support for timezone-aware
datetime. This setting is set to True when you create a new project using the startproject management command.

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

What is applications and projects in django

A

In Django, a project is considered a
Django installation with some settings. An application is a group of models, views, templates, and URLs. Applications interact with the framework to provide some specific functionalities and may be reused in various projects. You can think of the project as your
website, which contains several applications such as a blog, wiki, or forum, that can be used by other projects also.

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

create project in django

A

django-admin startproject myproject

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

create application in django

A

python manage.py startapp blog

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

Basic structure of application

A
app/
    \_\_init\_\_.py
    admin.py
    apps.py
    migrations/
        \_\_init\_\_.py
    models.py
    tests.py
    views.py

admin.py - where you register your models to include them in admin django site
apps.py - include main configuration of app
migrations/ - contain database migrations of your application
models.py - data models of your application
tests.py - test for your application
views.py - the logic of your application goes here - each view receives HTTP request, process it and return response

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

In order for Django to keep track of our application and be able to create database tables for its models, we have to activate it. To do this

A

edit the settings.py file and add blog.apps.BlogConfig to the INSTALLED_APPS setting.

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

to create an initial migration for our Post model of blog application. In the root directory of your project, run the following command:

A

python manage.py makemigrations blog

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

The WHAT command takes migration names and returns their SQL without executing it.

A

python manage.py sqlmigrate blog 0001

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q
specify a custom database name for your model in the
Meta class of the model using the WHAT attribute.
A

db_table

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

migrate to sync databases

A

python manage.py migrate

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

creating a superuser

A

python manage.py createsuperuser

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

adding model to admin site

A

in admin.py of application write:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

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

Customizing the way models are displayed

A

in admin.py of application write:

from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘slug’, ‘author’, ‘publish’, ‘status’)
list_filter = (‘status’, ‘created’, ‘publish’, ‘author’)
search_fields = (‘title’, ‘body’)
prepopulated_fields = {‘slug’: (‘title’,)}
raw_id_fields = (‘author’,)
date_hierarchy = ‘publish’
ordering = (‘status’, ‘publish’)

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

Run shell

A

python manage.py shell

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

get method of Model.
for example:
user = User.objects.get(username=’admin’)

A
The get() method allows you to retrieve a single object from the database. Note that this method expects a result that matches the query. If no results are returned by the database, this method will raise a DoesNotExist exception, and if the database returns more than
one result, it will raise a MultipleObjectsReturned exception.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

create a db Post and save it to database

A

post = Post(title=’Another post’, slug=’another-post’, body=’Post body.’)
post.save()

and in a single operation:

Post.objects.create(title=’One more post’, slug=’one-more-post’, body=’Post body.’)

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

A QuerySet is

A

a collection of objects from your database that can have several filters to limit the results.

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

To retrieve all objects from a model Post

A

all_posts = Post.objects.all()

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

retrieve all posts published in the year 2017 using the QuerySet

A

Post.objects.filter(publish__year=2017)

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

retrieve all posts published in 2017 by the author with the username admin

A

Post.objects.filter(publish__year=2017, author__username=’admin’)

or

Post.objects.filter(publish__year=2017) \
.filter(author__username=’admin’)

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

Queries with field lookup methods are built using two underscores, for example,

A

publish__year , but the same notation is also used for accessing fields of related models, such as author__username .

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

You can exclude certain results from your QuerySet using the exclude() method of the manager. For example, we can retrieve all posts published in 2017 whose titles don’t start with Why

A

Post.objects.filter(publish__year=2017) \

.exclude(title__startswith=’Why’)

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

You can order results by different fields using the order_by() method of the manager. For example, you can retrieve all objects ordered by
their title , as follows

A

Post.objects.order_by(‘title’)

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

Ascending order is implied. You can indicate descending order with a negative sign prefix, like this

A

Post.objects.order_by(‘-title’)

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

If you want to delete an object, you can do it from the object instance using

A
the delete() method:
post = Post.objects.get(id=1)
post.delete()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

QuerySets are only evaluated in the following cases

A
  • The first time you iterate over them
  • When you slice them, for instance, Post.objects.all()[:3]
  • When you pickle or cache them
  • When you call repr() or len() on them
  • When you explicitly call list() on them
  • When you test them in a statement, such as bool() , or , and , or if
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

the default manager of every model that retrieves all objects in the database

A

objects

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

There are two ways to add managers to your models

A

you can add extra manager methods or modify initial manager QuerySets

*The first method provides you with a QuerySet API such
as Post.objects.my_manager() , and the latter provides you with Post.my_manager.all() . The manager will allow us to retrieve posts using Post.published.all() .

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

get_queryset() method of a manager returns the

A

QuerySet that will be executed.

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

A Django view is just a

A

Python function that receives a web request and returns a web response

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

Create a view to display a list of posts

A

from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
    posts = Post.published.all()
    return render(request, 'blog/post/list.html', {'posts': posts})
41
Q

that this parameter is required by all views.

A

request

42
Q

what returns render function of view

A

HttpResponse object

43
Q

If using path() and converters isn’t sufficient for you, you can use

A

re_path() instead to define complex URL patterns with Python regular expressions.

44
Q

to create view and url

A
  1. create view in views of application
  2. create urls.py in application folder
  3. add url to project:
    path(‘approute/’, include(‘app.urls’, namespace=’app’)),
45
Q

URL namespaces have to be unique across your entire project. URLs easily by including the namespace,
building them, for example for app blog

A

blog:post_list

46
Q

The convention in Django is to add a WHAT method to the model that returns the canonical URL of the object.

A

get_absolute_url()

47
Q

reverse() method that allows you to

A

build URLs by their name and passing optional parameters

48
Q

Django has a powerful template language that allows you to specify how data is displayed. It is based on template {1}, template {2}, and template {3}

A

1) tags
2) variables
3) filters

49
Q

Template tags control the rendering of the template and

look like

A

{% tag %}

50
Q

Template variables get replaced with values when the

template is rendered and look like

A

{{ variable }}

51
Q

Template filters allow you to modify variables for display

and look like

A

{{ variable | filter }}

52
Q

{% load static %} tells Django to

A

load the static template tags that are provided by the django.contrib.staticfiles application.

After loading it, you are able to use the {% static %} template filter throughout this template

53
Q

how pagination works

A
  1. We instantiate the Paginator class with the number of objects we want to display on each page.
  2. We get the page GET parameter that indicates the current page number.3. We obtain the objects for the desired page calling the page() method of Paginator .
  3. If the page parameter is not an integer, we retrieve the first page of results. If this parameter is a number higher than the last page of results, we will retrieve the last page.
  4. We pass the page number and retrieved objects to the template.
54
Q

Class-based views offer advantages over function-based views for some use cases. They have the following features:

A
  • Organizing code related to HTTP methods, such as GET, POST, or PUT , in separate methods instead of using conditional branching
  • Using multiple inheritance to create reusable view classes (also known as mixins)
55
Q
def post_list(request):
    object_list = Post.published.all()
    paginator = Paginator(object_list, 3)  # 3 posts in each
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'blog/post/list.html', {'page': page, 'posts': posts})

equivalent for class based view

A
class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 3
    template_name = 'blog/post/list.html'
56
Q

Django’s ListView generic view passes the selected page in a variable called

A

page_obj

57
Q

Django comes with two base classes to build forms:

A

Form : Allows you to build standard forms

ModelForm : Allows you to build forms tied to model instances

58
Q

Forms can reside anywhere in your Django project. The convention is to place them inside a

A

forms.py file for each application.

59
Q

define the configuration of an external SMTP server by adding the following settings in the settings.py file of your project:

A

EMAIL_HOST: The SMTP server host; the default is localhost
EMAIL_PORT: The SMTP port; the default is 25
EMAIL_HOST_USER: Username for the SMTP server
EMAIL_HOST_PASSWORD: Password for the SMTP server
EMAIL_USE_TLS: Whether to use a TLS secure connection
EMAIL_USE_SSL: Whether to use an implicit TLS secure
connection

60
Q

If you cannot use an SMTP server, you can tell Django to write emails to the console by adding the following setting to the settings.py file:

A

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

61
Q

If you don’t define the related_name attribute, Django will use the

A

name of the model in lowercase, followed by _set (that is, comment_set ) to name the manager of the related object back to this one.

62
Q

Creating forms from models

A
from .models import Comment
class CommentForm(forms.ModelForm):
     class Meta:
          model = Comment
          fields = ('name', 'email', 'body')
63
Q

module is a reusable application that primarily offers you a Tag model and a manager to easily add tags to any model

A

django-taggit

64
Q

The WHAT QuerySet returns tuples with the

values for the given fields. If pass flat=True to it to get a flat list like [1, 2, 3, …] .

A

values_list()

65
Q

list of similar posts example

A

post_tags_ids = post.tags.values_list(‘id’, flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids)\
.exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count(‘tags’))\
.order_by(‘-same_tags’,’-publish’)[:4]

66
Q

Django provides the following helper functions that allow you to create your own template tags in an easy manner:

A

simple_tag : Processes the data and returns a string

inclusion_tag : Processes the data and returns a rendered template

67
Q

example of simple_tag

A

from django import template
from ..models import Post

register = template.Library()

@register.simple_tag
def total_posts():
    return Post.published.count()
68
Q

example of inclusion tag

A

from django import template
from ..models import Post

register = template.Library()

@register.inclusion_tag('blog/post/latest_posts.html')
def show_latest_posts(count=5):
    latest_posts = Post.published.order_by('-publish')[:count]
    return {'latest_posts': latest_posts}
69
Q

Using a sitemap, you will help crawlers

A

that index your website’s content.

70
Q

Django provides a SearchQuery class to

A

translate the terms into a search query object.

71
Q

Django provides the following class-based views to deal with authentication. All of them are located in django.contrib.auth.views :

A

LoginView : Handles a login form and logs in a user

LogoutView: Logs out a use

72
Q

Django provides the following views to handle password changes:

A

PasswordChangeView: Handles a form to change the user password
PasswordChangeDoneView: The success view the user is redirected to after a successful password change

73
Q

Django also includes the following views to allow users to reset their password

A

PasswordResetView: Allows users to reset their password. It generates a one-time use link with a token and sends it to the user’s email account.
PasswordResetDoneView : Tells users that an email—including a link to reset their password—has been sent to them.
PasswordResetConfirmView : Allows users to set a new password.
PasswordResetCompleteView: The success view the user is redirected to after successfully resetting the password.

74
Q

LOGIN_REDIRECT_URL:

A

Tells Django which URL to redirect after a successful login if no next parameter is present in the request

75
Q

LOGIN_URL:

A

The URL to redirect the user to log in (for example,

views using the login_required decorator)

76
Q

LOGOUT_URL

A

The URL to redirect the user to log out

77
Q

The best way to check whether the current user is authenticated is by accessing its read-only
attribute

A

is_authenticated

78
Q

If you see the logout page of the Django administration site instead of your own log out page

A

check the INSTALLED_APPS setting of your project and make sure that django.contrib.admin comes after YOUR application. Both templates are located in the same relative path, and the Django template loader will
use the first one it finds.

79
Q

You can provide a clean_() method to any of yourform fields in order to

A

clean the value or raise form validation errors for a specific field

80
Q

For Django to serve media files uploaded by users with the development server, add the following settings to the settings.py file of your project

A
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
81
Q

The static() helper function is suitable for development

A

but not for production use. Never serve your static files with Django in a production environment.

82
Q

Django also offers a way to substitute the whole user model with your own custom model. Your user class should inherit from Django’s

A

AbstractUser class, which provides the full implementation of the default user as an abstract model.

83
Q

Django has a built-in messages framework that allows you to

A

display one-time notifications to your users.

84
Q

You can create new messages using the add_message() method or any of the following shortcut methods:

A

success(): Success messages to be displayed after an action was successful
info(): Informational messages
warning(): Something has not yet failed but may fail imminently
error(): An action was not successful, or something failed
debug(): Debug messages that will be removed or ignored in a production environment

85
Q

The AUTHENTICATION_BACKENDS setting includes

A

the list of authentication backends for your project. By default, this setting is set as follows:
[‘django.contrib.auth.backends.ModelBackend’]

86
Q

The default ModelBackend authenticates users against

A

the database using the user model of django.contrib.auth

87
Q
An authentication backend is a class that provides the
following two methods
A

authenticate(): It takes the request object and user credentials as parameters. It has to return a user object that matches those credentials if the credentials are valid, or None otherwise. The request parameter is an HttpRequest object, or None if it’s not provided to authenticate() .
get_user(): Takes a user ID parameter and has to return a user object.

88
Q

Consider setting db_index=True for fields that you frequently query using filter() , exclude() , or order_by() .
ForeignKey fields or fields with unique=True imply the creation of an index. You can also use {2} to create indexes for multiple fields.

A

1) db_index=True

2) Meta.index_together

89
Q

slugify function

A

from django.utils.text import slugify

slugify(str)

90
Q

change input type in form ModelForm

A
class ImageCreateForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = ('title', 'url', 'description')
        widgets = {
            'url': forms.HiddenInput,
        }
91
Q

A bookmarklet is a

A

bookmark stored in a web browser that contains JavaScript code to extend the browser’s functionality

92
Q

AJAX comes from

A

Asynchronous JavaScript and XML

93
Q

CSRF

A

Cross-Site Request Forgery

94
Q

The Django request object provides an WHAT method that checks whether the request is being made with XMLHttpRequest , which means it is an AJAX request. This value is set in the HTTP_X_REQUESTED_WITH HTTP header, which is included in AJAX requests by most JavaScript libraries.

A

is_ajax()

95
Q

The ContentType model has the following

fields

A

app_label : This indicates the name of the application the model belongs to. This is automatically taken from the app_label attribute of the model Meta options. For example, our Image model belongs to the images application.
model : The name of the model class.
name : This indicates the human-readable name of the model. This is automatically taken from the verbose_name attribute of the model Meta options.

96
Q

The select_related method is for ForeignKey and OneToOne fields. It works by performing an

A

SQL JOIN and including the fields of the related object
in the SELECT statement.

Usage:
actions = actions.select_related(‘user’, ‘user__profile’)[:10]

97
Q

Django provides several signals for models located at

django.db.models.signals . Some of these signals are as follows

A

pre_save and post_save are sent before or after calling the save()
method of a model

pre_delete and post_delete are sent before or after calling the delete() method of a model or QuerySet

m2m_changed is sent when a ManyToManyField on a model is changed

98
Q

Django comes with a signal dispatcher that allows receiver functions to get notified when certain actions occur. Signals are very useful when you need your code to

A

do something every time something else happens. You can also create your own signals so that others
can get notified when an event happens.

99
Q

The following are some scenarios in which Redis suits pretty well

A

Counting: As you have seen, it is very easy to manage
counters with Redis. You can use incr() and incrby() for
counting stuff.
Storing latest items: You can add items to the start/end
of a list using lpush() and rpush() . Remove and return the
first/last element using lpop() / rpop() . You can trim the list
length using ltrim() to maintain its length.
Queues: In addition to push and pop commands, Redis offers blocking queue commands.
Caching: Using expire() and expireat() allows you to use Redis as a cache. You can also find third-party Redis cache backends for Django.
Pub/sub: Redis provides commands for
subscribing/unsubscribing and sending messages to
channels.
Rankings and leaderboards: Redis sorted sets with
scores make it very easy to create leaderboards.
Real-time tracking: Redis’s fast I/O makes it perfect for real-time scenarios.