Django-Basics Flashcards

1
Q

Command to start a project

A

django-admin startproject project_name .

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

How to create a new django app?

A

python manage.py startapp app_name

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

What are the bolierplate files generated when you create a django project?(6)

A

project_name
- __init__.py : just indicating that it is a package
asgi.py: provides asynchronous server gateway interface
wsgi.py: provides webserver gateway interface
urls.py: points to various url mapping in different apps within the projects
setting.py : contains all the configuration applied on the p[roject
manage.py : contains various commandline function executed during dev of a project.(ex like creating a ap,migrating.. etc…)

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

command to run the django dev server?

A

python manage.py runserver

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

What are the bolierplate files generated when you create a new django app?(6+1)

A

total: 6+1 files.
app_name
__init__.py: indicate this as package so that it can be imported in other appications
models.py : contains all django models
apps.py:configuration file for the app itself
views.py : contains all the views
admin.py: configuration file for django admin.
tests.py:contains the tests
migrate : all migration files will be stored here
__init__.py

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

How to add a new app to a django project?

A
  1. create the app
    python manage.py startapp app_name
    2.Add to the list of installed app in django project.
    • Open settings.py in main project directory.Insert the following entry to a list called “INSTALLED_APPS”
    • “app_name.app.App_nameConfig” (Last part shoul;d be the app_name in camel case and whole netry must be enclosed within a string.(why check this out??))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to update the database when new models are added?

A

Lets the app name be app_name
steps to follow:
1. python manage.py makemigrations app_name (name of the app is oiptional.It’s best practivce toa add itwhy?? seperately mentioned in the migration files??)
2.python migrate

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

How to create a rootuser from cli?

A

python manage.py createsuperuser

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

How to register an model to admin?

A

1.Open admin file within the respective app
2.add following entry
from django.contrib import admin
admin.site.register(Model_name)

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

How to import ListView?

A

from django.views.generic import ListView

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

let the projet directory be as follows
main_app
sub_app

-> subapp contain a view called BookListView add this to the path pof the project.

A

from django.urls import path,include
from django.contrib import admin
urls = [
path(“admin/”,admin.site.urls),
path(“books/”,include(“books.urls”)) # note that the module is passed as string.again why????doe sboth of them work????
]
————————————-
sub_app/urls.py
—————————————
from django.urls import path
from .views import BookListView

urlpatterns=[
path(““,BookListView.as_view(),name=’book_list’)
]
—————————————

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

How to create a view object poining to a model and a templeate./give one example class?create a booklist view

A

from django.views.generic import ListView

class BookListView(ListView):
model=Book
template_name=”booklist_template.html” # again passed as string why???

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

Where will the django look for templates by default.?
Assume there is an app called book

A

Django first check for template file within templates/book/template_name.html within book directory first
Then it checks for templates/book/template_name.html within main project directory.

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

If we have a Listview with modelname book how can we access this model details from it’s template files?(objact name to be used)

A

default name is [model_name]_list.So for the current ex obj name will be book_list

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

How to use for loop ithin templates.Show an example?

A

{% for book in book_list%}

<h3>Book Name {{book.title}}</h3>

<h3>
{%% endfor %} #Do nopt forget to close the loop
----------------------------------------------------------</h3>

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

Cli command to run tests in django?

A

python manage.py test

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

What is reverse() used for?

A

reverse function takes a string as an arg and return the path (as string?? check this) with passed argument as it’s name.

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

While creating tests how to create the database object first in django?

A

Every test object must inherit from TestCase object(from django.test import TestCase)
Inside test obj create a class method setUpTestData() to set up the data.Following example gives a clear idea
——————————————
class BookTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.book= Book.objects.create(…) # book is one of the models that is imported to this file.
def test_booktest(self): #ex test .Not that all the test must start with test_
self.AssertEqual(self.book.title,”dsnmkjd”) #Note that the book obj defined earlier is accessible using self.Assertion methods are availbale as inherited methods from TestCase obvject.

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

How to set a url for a model?

A

Override get_absolute_url function in model return reverse(namespace:url_name,args)

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

What does unique_for_date arg in slug field accomplish?
Lets assume the following field
slug=models.SlugField(unique_for_date=’publish’)?
Do we need to call makemigrations and migrate after this?

A

After applying the above argument slug and publish date must be unique for all the elements in the model.
The entry does not make any changes on the internal database.The whole restriction is applied at django level.Although e have to still apply migrations to save the model changes so the it is enforced by the django.

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

How to implement pagination in function based views?

A

Use Paginator object from django.core.paginator
data=Model.objects.all()
paginator=Paginator(queryset,max_elements_per_page)
data=paginator.page(page_number)

22
Q

What are some of the exceptions (2) that must be handled while implementing pagination??

A

EmptyPage,PageNotAnInteger example

23
Q

How is csrf checked by default middleware in django?

A

For every request(even if it do not hve any forms) a csrf token is generated by the middleware.This csrf token is checked while entering the view and view has csrf restrictions.if the csrf token in the form in request is not the one stored by the middleware errro is thrown.If tokn itself is missing error is thrown
Note: you can use @csrf_exempt decorator to prevent checking this
How many csrf tokens are stored by the middleware before they replace iot with new ones?Is it based on a expiry time??
csrf secret is changed every time user logs in? although csrf token seems to chenage everytime with new request all the csrf tokens while the user is loggen in containes the same secret.

24
Q

Basic steps to create a customuser?

A

from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
….
….
**********
in main settings.py add the folling entry at the end
->. AUTH_USER_MODEL=’[app_name].CustomUser’. # point it to the class that we are using as user object class

25
Q

What is a djangio backend?How is it used?What is the default one?

A

Django Backend is a class containing authenticate(main one) function.It is used to authenticate the user.
We can define several backends.Default one is django.contrib.auth.backends.ModelBackend.You can create your own backend by implementing functions like authenticate.(research further to et exact details)
Process
Django tries authenticating with given credentials on each backend one by one in the order in which they where defined.
if one of them fails the next one is checked.
If anyone of them throws permission denied error.User is set to none and stops fiurther checking and the functionexits.

26
Q

Should user model should be the first migration ?

A

Yes.Research why?
https://docs.djangoproject.com/en/4.1/topics/auth/default/

27
Q

Do we need to create a custom user manager when we define a customuser?

A

If your user model defines username, email, is_staff, is_active, is_superuser, last_login, and date_joined fields the same as Django’s default user, you can install Django’s UserManager,

28
Q

How to create a custom amanager?

A

(One way to do this is as follows.I don’t know if there is any other ways.THe obne mentioned is from doc)
create a class inhering BaseUserManager(under models.BaseUsermanager)
override 2 functions->create_user()and create_superuser().
-Both f()’s should accept username field(whichever field you are using as username) and other required field for creating the user object.

29
Q

What are the default forms available for authentication purposes?

A

1.AuthenticationForm. -> uses the username field mentioned within the form as USERNAME_FIELD
2.SetPasswordForm
3.PasswordChangeForm
4.AdminPasswordChangeForm
5.PasswordResetForm
6.UserCreationForm
7.UserChangeForm

30
Q

Out of the auth forms avail which one of them need to be changed when a custom user model isdefined?

A

PasswordResetForm-> Need to be changed if underlying reset mechanism is chaned(check for details)
usercreation and userchange form has to be changed only if there are any extra fields in the new model that is not there in the default user model.

31
Q

What is “related_name” in field classes?.I it only applicable to Forign key?

A

it give the reverse relateion.name for reverse_relation if not given is automatically created by django for certain fields .
Ex:ForignKey. (idk if any other field has this)

32
Q

Difference b/w “auto_now” vs “auto_now_add” arg in field contructor class?

A

It is seen applied to date and datetimefield.auto_now updates the value everytime user change the model whereas auto_now_add is added when the model is created fior the first time.

33
Q

How to create a new model say post in Django?

A

from Django.db import models

class Post(models.Model):

33
Q

How to create a new model say post in Django?

A

from Django.db import models

class Post(models.Model):

34
Q

How to access the list values in template for ListView?
(3 different ways)

A

1.It will be pushed to context variable:object_list.We can use this to access inside the template.
2.If we mention model same data will be available in a var called (model_name.lower())_list.Note that same data is available in object_list and with the above mentioned name.
3.We can also set our own name to be used inside the template.It is done by overriding the var obj context_object_name and set it to the ring that we want to use.

35
Q

How to capture values from url-path and make Django pass it to the view function?

A

by defining the values that need to be passed inside angular bracket while definingg in url pattern as shown below.
Ex:
path(“customers/users///”)
here int is called path converters.if not present it will be considered as string.

36
Q

What is a path converter in Django?
Name different path convertors available in Django?(5)

A

path convertors convert part of a url to the mentioned type and pass it as argument to view function.(Not exactly sure)
ex: path(‘/customer/’) here str is a path convertors.
Different path convertors supported by Django-
1.int
2.str
3.uuid
4.slug
5.path-any non empty string lets you capture string along with / b/w them.if we use str it only captures a segment b/w ‘/’.

37
Q

Can we create custom path convertors?

A

Yes.

38
Q

How to give default values for view parameters?

A

mention it as a default parameter inside the respective view.

39
Q

If you are return HttpResponse obj in Django how to mention the status code?

A

HttpResponse(status=201)

40
Q

How to send a http404 response

A

from Django.http import Http404

def custom_view(request):
raise Http404(“Page does not exist”)
Inorder to sent a custom page for 404add 404.html page in templates(top level).

41
Q

decorator to restrict view to certain http methods?

A

from django.views.decorators.http import require_http_methods

@require_http_methods([‘GET’,’POST’])
def handle_view(request):
pass

42
Q

various arg taken by render f()

A

render(request, template_name,context=None,content_type=None,status=None,using=None)
using:name of the template engine,
content_type: default text/html
status : default 200

43
Q

urls allowed using redirect

A

a model object with get_absolute_url
url name -> will be resolved internally using reverse
absolute or relative url

44
Q

shortcut f() to get the list or a single object and if not present returns a 404 message

A

get_object_or_404(obj,klass,kwargs)
get_list_or_404(klass, *args, **kwargs)¶
obj:model, manager or QuerySet
kwargs-> lookup parameters which will be passed to filter
klass=Q objects(??) query instance objects: title_start_with

45
Q

What are the functionalities provided by the field classes in model?(3)

A

1.let Django know the type of data to store in database
2.default widget to use when rendering form
3.default validations used in admin and forms

46
Q

common used field arguments provided by Django?

A

blank
null
default
choices -> get_FOO_display()
unique -< boolean
help_text

47
Q

How to give verbose name for field?

A

Verbose name if avail is given as the first argument of the field object.It must be string.
IT is not available for relation type fields like OnetoOne,ForighnKey,ManytoMany as the first arg as first argument will be the linking object reference.In case of these three field verbose name is given as named argument verbose_name

48
Q

How to use a custom intermediate model?

A

by specifying the model object using ‘through’ named arg.this intermediate model can contain additional data common to both while the relation happens

49
Q

How to pass through table additional data inside f() like add, create,set

A

as named_arg => through_defaults
a dictionary is passed.