Module 1 - Django

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is Django's template language called?

Django Templates

What is Django's testing framework called?

Django Test Framework

What's the name of the important variable name in settings.py that has a list of all of the installed Django apps?

INSTALLED_APPS

How can you secure a Django application from common security threats such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF)?

Input validation, escaping user input, using parameterized queries, enabling CSRF protection, and setting secure cookie settings.

What is Django's authentication system?

It provides a way to manage user accounts and passwords

What file do you use to tell the Django admin about your models?

admin.py

In what file do we register the URLs for our view functions? a.) models.py b.) settings.py c.) urls.py d.) views.py

c.) urls.py

What method on a Django model do you call to get all of the instances of that model from the database?

.objects.all()

What method can you call on a Django model to create a new instance of the model AND save it to the database in one go?

.objects.create()

If you create an instance of a model by calling the class name, what do you need to call to get it to actually save the data to the database?Example:ExpenseCategory(name="category 1", owner=admin)

.save()

What do you have to define in order to get Django to show your models in the admin?

1) A class that inherits from admin.ModelAdmin2) Call admin.site.register with your model and your modeladmin class. or 2) Use the @admin.register(model) decorator with your modeladmin class.

What are two ways you can ensure that someone has to be logged in to access a view?

1. Inheriting from LoginRequiredMixin for class based views 2. Using the @login_required decorator for function based views.

Organizing code is a way that we can make it easier for us to find where we need to make changes, either because we want to add a new feature, or we need to fix a bug. What are three ways that we organize code in Python? How do each of those help us?

1.) Classes - Classes organize our code by grouping functions with variables that are related to them 2.) Functions - Functions organize our code by isolating bits of code into smaller pieces 3.) Modules - Modules organize our code by grouping similar functionality together across different files

From the list below, what three things can the Django Web framework do? a.) Allows you to ignore all good programming practices b.) Combines data and HTML to create web pages c.) Returns HTML to the browser d.) Gets requests from people's browsers

1.) Combines data and HTML to create web pages 2.) Gets requests from people's browsers 3.) Returns HTML to the browser

Django model classes are an important part of the Django application. Please identify four ways that Django model classes help us when we write our Web application.

1.) Helps us organize our data into database tables 2.) Gives us an easy way to change data using forms 3.) Allows us to only accept certain data types by specifying the data type of each attribute 4.) Allow us to view all of the different types available in the admin panel

Identify four ways that models, views, forms, and templates in Django work together to make a working Web application that can show and accept data.

1.) Views use models to display the data from the database 2.) Models pull data from the database 3.) Templates render forms 4.) Forms use models to determine what fields to show

What is a Django context?

A dictionary of variables that are passed to a Django template

What is a Django form?

A form is a Python class that generates HTML forms and handles form data

What is the filter() method?

A method that returns a QuerySet containing all the objects that match the specified query criteria.

What is a Django model?

A model is a Python class that represents a database table

What is a Django view?

A view is a Python function that takes a web request and returns a web response

What is a Django signal?

A way for different parts of a Django application to communicate with each other

What is the role of the Django Middleware in a web application?

A way to modify request/response objects globally before they are processed by the view. Middleware can be used to add functionality to your application, such as authentication, caching, and compression.

What is the purpose of the urlpatterns list in the urls.py file?

It associates a URL pattern with a view. It gives a name to the path/view combination so we can use it in templates with the url tag.

What is Django's CSRF protection?

It is a security feature that protects against cross-site request forgery attacks

What is the purpose of Django's django-admin.py command-line tool and how can you use it to manage your Django project?

It is a utility for managing Django projects. You can use it to create new Django projects, manage database migrations, run the development server, and perform other administrative tasks.

What is the purpose of Django's middleware?

It is used to process requests and responses before they reach the view or after they leave the view

What is Django's built-in caching framework and how can you use it to improve the performance of your application?

It provides a way to cache the results of expensive database queries, view functions, or templates. You can use the 'cache_page()' decorator to cache the entire response of a view function, or the 'cache' template tag to cache the output of a template fragment.

What is the purpose of a Django Model?

It provides the ability to save and retrieve data from the database. It defines which columns we want in our database. It is used by Django to create migration files.

The context dictionary serves what purpose in Django?

It provides the variables to the Django template. Any key in the dictionary becomes a variable inside the template.

If you do not specify a related_name on a Foreign Key , what is the default name that Django will provide.

It takes the model name, lowercases it and adds on _set

If you have a class view that inherits from ListView, how does it determine the name of the object in the context?

It takes the model parameter, lowercases, and adds "_list" to it.

What is the purpose of the INSTALLED_APPS list in settings.py?

It tells Django about all the Django apps in our project and makes the views, models and urls available.

What does the acronym "MVC" stand for?

Model-View-Controller

How do you tell Django you do not want a related_name on a Foreign Key

Set the related_name to '+' or end the name with a '+'

What is the purpose of Django's URL dispatcher?

The URL dispatcher is used to map URLs to views in a Django web application

What is the purpose of Django's built-in admin interface?

The admin interface allows users to manage the data in their database through a web interface

What is the third parameter to the "render" method called?

The context dictionary

What is the purpose of a migration file in Django?

The migration files are automatically created and contain code to create the tables and columns in the database when the django "migrate" command is run.

What is the purpose of Django's migration system?

The migration system is used to manage changes to the database schema over time

How can you optimize Django's ORM for performance in situations where you are dealing with a large amount of data?

There are several ways to optimize Django's ORM for performance with large amounts of data, including using select_related() and prefetch_related() to reduce the number of database queries, using values() and values_list() to retrieve only the necessary data, and using database indexes to speed up queries.

What is the purpose of Django's template tags?

They are used to perform logic and display dynamic content in a Django template

What is the get() method?

This method returns a single object that matches the specified query criteria, or raises a DoesNotExist exception if no object is found.

What is the purpose of a View in Django?

To process the incoming request. To process incoming data from a form To use the model to save and retrieve data from the database To create a context object to be used by the template To send a response back to the browser Optionally to redirect the browser to another page

What is the purpose of the urls.py file inside a Django App folder?

To register URL paths for views that are part of that app

What is the purpose of the urls.py file in the Django project folder?

To register URLs for the other urls.py files for the other Django apps.

How do you display the value of a variable in a Django template?

Using the double curly brace syntax - {{ }}

On your product detail page, you'd like to show other products that are similar to the one the customer is currently viewing. Where would you put that data so you can sell more products? a.) Add it to the context for the template that will be rendered b.) Add it to the request.user object so that it's for that user c.) Add it to the form for validation with form.is_valid()

a.) Add it to the context for the template that will be rendered

What is Django's built-in user authentication system called? a.) Auth b.) UserAuth c.) LoginAuth d.) DjangoAuth

a.) Auth

Which of the following actions would cause a comment to be deleted? class Comment(models.Model): content = models.TextField() blogpost = models.ForeignKey( BlogPost, on_delete=models.CASCADE, ) author = models.ForeignKey( User, on_delete=models.PROTECT, ) a.) Deletion of the related blogpost object b.) Deletion of the related author object c.) Neither

a.) Deletion of the related blogpost object

Given this code: def mystery(request): if request.method == "POST": form = WidgetForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] widget = Widget.objects.create(name=name) return redirect(widget) else: form = WidgetForm() context = { "form": form } return render(request, "template.html", context) What does it do? a.) If the request is a POST and the form is valid, creates a new Widget b.) If the request is a GET and the form is valid, creates a new widget c.) If the request is a POST and the form is valid, updates a new widget

a.) If the request is a POST and the form is valid, creates a new Widget

Given this code: def create_blog_post(request): if request.method == "POST": form = BlogPostForm(request.POST) if form.is_valid(): blog_post = form.save(False) blog_post.author = request.user blog_post.save() return redirect("blog_post_detail", id=blog_post.id) else: form = BlogPostForm() context = { "form": form, } return render(request,"blog_posts/new.html", context) Why do we pass False to form.save in this code? a.) To assign the current user as the post author before it's saved b.) To assign a selected user as the post author before it's saved c.) To validate that the user has permission to create a blog post

a.) To assign the current user as the post author before it's saved

What is the purpose of Django's ORM (Object-Relational Mapping) layer? a.) To interact with the database b.) To create HTML templates c.) To handle user authentication d.) To manage the web application's URL routing

a.) To interact with the database

You would like to add a last_update field to a model you're working on. You would like for the field to get updated every time there's any change to the record. Adding which parameter to your DateTimeField will accomplish this goal? a.) auto_now=True b.) auto_now_add=True c.) auto_update=True

a.) auto_now=True

What two things from the list below does a Django app handle for us? a.) data models b.) everything c.) HTML templates d.) project settings

a.) data models and c.) HTML templates

Which command is used to start a new Django project? a.) django-admin startproject b.) startproject django-admin c.) newproject django-admin d.) django-admin newproject

a.) django-admin startproject

Django is complaining that one of the fields below is missing a required parameter: class Thing(models.Model): name = models.CharField() created_date = models.DateField() number = models.PositiveIntegerField() email = models.EmailField() Which field is it? a.) name = models.CharField() b.) created_date = models.DateField() c.) email = models.EmailField()

a.) name = models.CharField()

How do you create a Django superuser? a.) python manage.py createsuperuser b.) python manage.py createsuper c.) django-admin createsuperuser d.) django-admin createsuper

a.) python manage.py createsuperuser

Which command is used to run the development server in Django? a.) python manage.py runserver b.) python manage.py startserver c.) django-admin runserver d.) django-admin startserver

a.) python manage.py runserver

Which three of the following files are in a Django app? a.) admin.py b.) apps.py c.) manage.py d.) models.py e.) settings.py

admin.py, apps.py and models.py

If you want a DateField or DateTimeField to automatically populate with the current date everytime you save the instance, what option do you use?

auto_now

If you want a DateField or DateTimeField to automatically populate with the current date when you create a new instance, what option do you use?

auto_now_add

What is Django? a.) A programming language b.) A web development framework c.) A database management system d.) An operating system

b.) A web development framework

Consider this code: class Author(models.Model): name = models.CharField(max_length=200) class Book(models.Model): title = models.CharField(max_length=200 author = models.ForeignKey( Author, related_name="books", on_delete=models.CASCADE ) You're creating a page that will show the details about a single book and will also show a list of all books by the same author. Which of the following Querysets would work best for your view? a.) Book.objects.all() b.) Book.objects.get(id=id) c.) Author.objects.get(id=id)

b.) Book.objects.get(id=id)

Which of the following is not a component of Django's MTV (Model-Template-View) architecture? a.) Model b.) Controller c.) View d.) Template

b.) Controller

Assume that you just wrote a Car model class and now you're playing around with it in the Python shell to test it out. Read the code below and then answer the question about the state of car at the end. car = Car( manufacturer="honda", model="CR-V", year=2013, color="green" ) car.save() car.color = "blue" What is the state of car? a.) Both the database and the car have the color blue b.) The car has the color blue, but the database has the color green c.) Both the database and the car have the color green

b.) The car has the color blue, but the database has the color green

You're writing a new view to add a page to your site that allows a user to create a new game. It almost works. The game is getting created, but it's not associated to the user who created it. Where is the best place to set the current user as the person who created that Game instance? a.) Set it in the HTML of the games/new.html template when it is rendered b.) Use form.save(False) and set the created by on the returned object c.) Set it only if the request.method is "GET"

b.) Use form.save(False) and set the created by on the returned object

Your website has a page that you'd like to make available only to logged-in users. The view for the page is implemented using a function-based view. Which of these Django-provided tools is the best tool for the job? a.) Use the LoginRequiredMixin as the first entry in the view's inheritance list b.) Use the @login_required decorator just before the view function c.) inside the view, test if request.user.is_authenticated:

b.) Use the @login_required decorator just before the view function

Notice in the code below, that the related_name parameters was not provided in ForeignKey. class Comment(models.Model): content = models.TextField() blogpost = models.ForeignKey( BlogPost, on_delete=models.CASCADE ) What will be the "related" name on the BlogPost model for the collection of Comment instances for that BlogPost model? a.) comments b.) comment_set c.) Django will not create one automatically

b.) comment_set

You just created a new view for your Django app named pets for your Django project named vet_office. Now you have to tell Django what url path to use for the view. Where does this code go? a.) pets/admin.py b.) pets/urls.py c.) vet_office/settings.py

b.) pets/urls.py

Every view function has what first parameter? a.) response, the response to the browser b.) request, the request from the browser c.) name, the name of the function

b.) request, the request from the browser

What is the default database used by Django? a.) MySQL b.) PostgreSQL c.) SQLite d.) Oracle

c.) SQLite

Consider this code. class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ( "vendor", "total", "tax", "date", "category", "account", ) If the fields attribute is commented out or not included, as shown in the code above, Django will do what? a.) The form will automatically use all of the fields b.) The form will automatically use all of the fields, except the primary key field c.) The form will raise an error about not have a fields or exclude attribute

c.) The form will raise an error about not have a fields or exclude attribute

What code below was used to register the Book model with the Admin page? a.) admin.Book.register.site() b.) admin.register(Book) c.) admin.site.register(Book)

c.) admin.site.register(Book)

Given this code, where the check_for_solution function checks to see if the person has solved a puzzle, and the prepare_puzzle function sets up the puzzle to be shown in the template: def puzzle(request): result = None if request.method == "POST": result = check_for_solution(request) puzzle = prepare_puzzle() return __________________ Which of the following lines will make both result and puzzle available in the template by creating a context? a.) render(request, "things/puzzle.html", result, puzzle) b.) render(request, "things/puzzle.html", [result, puzzle]) c.) render(request, "things/puzzle.html", {"result": result, "puzzle":puzzle})

c.) render(request, "things/puzzle.html", {"result": result, "puzzle":puzzle})

Given this code: def store_detail_view(request, id): store = get_object_or_404(Store, id) store_location = store.get_location() weather_data = get_weather_data(store_location) context = { "the_store": store, "weather_data": weather_data, } return render(request, "stores/detail.html", context) Inside of the template, what "variable" would you use to access the weather information? a.) store.weather_data b.) the_store.weather_data c.) weather_data

c.) weather_data

Which of the following is a Django app? a.) HTML b.) CSS c.) SQLite d.) Authentication

d.) Authentication

Which of the following is not a Django template engine? a.) Jinja b.) Django Templates c.) Mustache d.) Twig

d.) Twig

What method do you define on your Django models that lets you control how your instances show up in the Django admin?

def __str__(self):

What command do you type to create a new Django Project?

django-admin startproject <name> <directory> (and directory is often a . if you already have a folder for your project)

If you want to have all your pages contain the same navigation links or other content, what two Django Template tags do you use to accomplish this?

extends and block

How do you get the name of the default Django User Model as a string?

from django.conf import settingssettings.AUTH_USER_MODEL

How do you import the built in User model?

from django.contrib.auth.models import User

How would you import a model named "Post" from a Django app folder named "posts"

from posts.models import Post

How would you import a view into a urls.py file for a view function called list_posts in a Django app called "posts"

from posts.views import list_posts

By default, what do we type into the browser to see the Django Web server running on our own computer?

localhost:8000

Which of the following model field types do we use for strings in a Django model? a.) models.CharField b.) models.VarCharField c.) models.StringField

models.CharField

What method on a Django model do you call to retrieve one specific instance?

objects.get()

What command do you use to install Django?

pip install Django

When you access the related_name on a model instance, how do you go about getting all the instances of that related_name? Example, let's say you had an instance of a Post and you want to get the related_name "comments" and get all of the comments.

post.comments.all()

What command do you use in Django to create the files in the migrations folder?

python manage.py makemigrations

What command do you run to create the tables in your database?

python manage.py migrate

What command in Django do you use to be able to interactively query your models to try things out and experiment?

python manage.py shell

What command in Django do you use to create a new Django app?

python manage.py startapp <name>

How can you tell if a request is a GET or a POST?

request.method == "POST" or request.method == "GET"

How do you access the currently logged in user in a Django function view?

request.user

What symbol do you use in a Django template to use a django template filter?

the pipe symbol - |

What symbols do you use in a Django template to indicate a django template tag?

{% %}

In a Django template, how do you loop over a list of items and display HTML for each item?

{% for item of list %} { % endfor %}

If you want HTML in a template to only show up when a user is logged in, what do surround your HTML with?

{% if user.is_authenticated %} {% else %} {% endif %}


संबंधित स्टडी सेट्स

Network Auth and Security Chapter 1-22

View Set

Statisztika 2/II. zh fogalmak - tesztek

View Set