Django Test Answers 2019


Share Django Test Answers

Posted on June 7, 2019


93 Test Questions:

1. Which of the following is false about the django.models.SlugField() model field?

• It is used when performing a query, or as a part of a URL, since by default it ensures uniqueness.
• To create a slug based on another field automatically in the admin, prepopulated_fields has to be used.
• It can only contain letters, numbers, underscores or hyphens.
• Slugs can created in Django templates using the builtin filter, «django.template.defaultfilters.slugify», formatted as {{ some_text|slugify }}.

2. What does the «with» template tag do?

• It adds its argument to the value.
• It caches a complex under a simpler name.
• It filters the contents of the blog through one or more filters.
• None of these.

3. Which of the following statements is true about the django.template.RequestContext class?

• It takes a Context object as its first argument.
• It takes an HttpRequest as its first argument.
• It does not automatically the context with variables.
• It can only be given one context processor.

4. Consider the following Python string representing a human readable date and time: dt = ‘Jan 14 2009 11:00PM’
Which of the following code snippets will convert the above string to a Python Datetime object that is suitable for a django.models.DateField?

• date_object = time.strptime(dt, ‘%b %d %Y %I:%M%p’)
• date_object = datetime.strptime(dt, ‘%b %d %Y %I:%M%p’)
• date_object = datetime.strptime(dt, ‘%B %D %Y %I:%M%p’)
• date_object = time.strptime(dt, ‘%b %d %Y %I:%M%p’)

5. Which of the following is not a predefined log level in Django?

• DEBUG
• INFO
• WARNING
• FATAL

6. What is the best way to extend the Django user model with extra custom fields in addition to the fields already provided?

• Use a a proxy model based on django.contrib.auth.models.User.
• Subclass django.contrib.auth.models.AbstractUser and add the extra fields.
• Subclass django.contrib.auth.models.AbstractBaseUser and add the extra fields
• Use a one-to-one relationship to a model containing the extra fields.

7. Which of the following statements about database transactions in Django is false?

• «atomic» blocks allows the creation of blocks of code within which the atomicity on the database is guaranteed.
• «atomic» blocks cannot be nested.
• «atomic» can be used as a decorator.
• «atomic» can be used as a context manager.

8. Which of the following statement is false about the django.http.HttpRequest.get_host() method ?

• If DEBUG = False and ALLOWED_HOSTS= [] the method will raise SuspiciousOperation exception resulting in an HTTP Error 500 Internal server error.
• The method will fail when the host is behind multiple proxies, in this case one solution is to use middleware which will rewrite the proxy headers.
• This method is invoked if some code accesses the Host header from request.META, thus providing a security measure to prevent an attacker from poisoning caches and password reset emails with links to malicious hosts by submitting requests with a fake HTTP Host header.
• The method uses information from the HTTP_X_FORWARDED_HOST and HTTP_HOST headers, in that order, or a combination of SERVER_NAME and SERVER_PORT if the latter does not provide a value.

9. Which of the following is a built-in BaseCommand subclass?

• AppCommand
• HelperCommand
• HandlerCommand
• DBCommand

10. Consider the following code snippet for a Django Model:
class Salary(models.Model):
amount = models.PositiveIntergerField(help_text=’eg 8000′)
retired = models.BooleanField(help_text=’True if above average’) ………..
Which of the following will correctly produce a QuerySet of all Salary objects where retired == True and amount != 7300?

• results = Salary.objects.exclude(retired=true, amount__lt=7300).exclude(retired=true,amount__gt=7300)
• from django.db.models import Q results = Salary.filter(~Q(amount=7300),retired=True)
• results = Salary.objects.filtered(retired=True, amount__ne=7300)
• from django.db.models import Q results = Salary.filter(Q(amount=7300),retired=True)

11. Which of the following statements is true about Django’s default implementation of the authentication system?

• Django stores passwords in plain text on the user model.
• It returns a UserAccount object is the password for a given username is authenticated.
• Permissions can only be set on a per type of object basis.
• django.contrib.auth will ensure that add, change and delete permissions are created for each Django model defined in an installed application.

12. What does the django.core.context_processors.static() method do?

• It takes a path and urljoins it with the static prefix STATIC_URL.
• It adds STATIC_URL to every template context rendered with RequestContext contexts.
• It populates a template variable with the static prefix STATIC_URL to be used as a variable or directly.
• None of these.

13. Which of the following statements are true about the ImageField class?

• It inherits all attributes and methods from the FileField class.
• It validates that the uploaded object is a valid image.
• Its instances are created as varchar(200) columns in the database.
• It’s default form widget is a ClearableFileInput.

14. Which of the following happens when process_exception() returns «None»?

• The template response will be applied.
• The response middleware will be applied.
• The default exception handling will be applied.
• None of these.

15. Consider two Django QuerySets query_set_1 and query_set_2 from two different models.
Which of the following code snippets is the most performant when concatenating the two QuerySets into one list?

• from itertools import chain result_list = list(chain(query_set_1,query_set_2))
• result_list = query_set_1 | query_set_2
• from django.db.models import Q result_list = Q(query_set_1) | Q(query_set_1)
• from itertools import chain result_list = chain(query_set_1, query_set_2)

16. Which of the following django.template.loader functions will take a list of template names and return the first template that exists?

• find_one_template
• find_template
• get_template
• select_template

17. Which of the following classes uses an HTTP 304 status code?

• HttpResponseNotModified
• HttpResponseRedirect
• HttpResponseForbidden
• HttpResponseServerError

18. Which of the following is not a built-in Django template loader class?

• file.Loader
• cached.Loader
• eggs.Loader
• app_directories.Loader

19. What is the default max_length value of a SlugField class in Django?

• 50
• 100
• 25
• 150

20. Which of the following gets called when a view raises an exception?

• view_exception()
• process_exception()
• execution_exception()
• controller_exception()

21. What is TRUE about django-admin.py makemessages command?

• Updates all messages in the database.
• Pulls out all the strings marked for translation and makes a message file in the locale directory.
• Both of the above
• None of the above

22. Which of the following is the correct way to specify a translation string?

• by using the function ugettext()
• by using the function ugettext_lazy()
• Both of the above
• None of the above

23. Which of the following are determined by Django using field class types?
Note: There may be more than one right answer.

• The database column type
• The default HTML widget to avail while rendering a form field
• Makemigrations
• All of the above

24. Which is the correct way to start a new django project? Assume new project is called ‘myproject’.

• django startproject myproject
• django-admin startproject myproject
• django newproject myproject
• startproject django myproject

25. Which of the following database is not supported by Django ORM?

• MySQL
• PostgreSQL
• MongoDb
• DynamoDb

26. Which is the correct way to start a new app inside a django project? [assume new app is called ‘myapp’]

• python manage.py startapp myapp
• python manage.py start myapp
• django-admin.py startapp myapp
• python manage.py new myapp

27. What are the features available in Django?
Note: There may be more than one right answer.

• Object-relational mapping (ORM)
• Internationalization
• Content Management System
• All of the above

28. Django is a web __ in Python to develop a web application.

• Programming
• Framework
• API
• Library

29. Is Django a content management system (CMS)?

• Yes, Django is a CMS
• Django is not a CMS
• Django is a Web framework and a programming tool that makes you able to build websites

30. In Django,to use file based session you have to set the SESSION_ENGINE settings to?

• django.contrib.session.backends.file
• django.controlsessions.backends.file
• django.contrib.sessions.backend.file
• django.contrib.sessions.backends.file

31. How can you set up static files in Django?

• set STATIC_ROOT in settings.py
• run manage.py collectsatic
• set up a Static Files entry on the PythonAnywhere web tab
• All of the above

32. Which of the following features are supported by Django?

• Development Environment
• Administration GUI
• Multilingual system
• Object Relational Mapping (ORM)
• All of the mentioned

33. Respecting Django modularity, What is the correct file path for a template file named “index.html” in Questions app?

• questions/index.html
• questions/templates/index.html
• questions/templates/index/index.html
• questions/templates/questions/index.html

34. Check all True facts about Django.
Note: There may be more than one right answer.

• Written in Python
• Desktop Application Framework
• Web Application Framework
• All of the above

35. Which option represents changing the last name of the user with id = 452 to “doe”?

• user = User.objects.filter(id=452)
user[0].last_name = “doe”
user[0].save()
• user = User.objects.get(id=452)
user.last_name = “doe”
user.save()
• user = User.objects.filter(id=452)[0]
user.last_name = “doe”
user.save()
• All of the above

36. What is the exception raised if you are using POST against this function?
from django.views.decorators.http import require_http_methods
@require_http_methods([«GET», «POST»])
def my_view(request):

• HttpResponseNotAllowed
• HttpResponseForbidden
• HttpResponseBadRequest
• No exception will be raised

37. Which of the following packages defines the function render_to_response?

• django.views
• django.shortcuts
• django.contrib.templates
• django.contrib.shortcuts

38. Users can create Posts, You want to hide the author field and assign the currently logged in user to be the author how can you do it ?

• [forms.py]
class PostForm(forms.ModelForm):
class Meta:
model = Post
exclude = (‘author’,)
[views.py]
def home(request, template_name=’post/home.html’):
if request.method == ‘POST’:
post_form = PostForm(request.POST) if post_form.is_valid():
post_form.save()
else:
post_form =PostForm(initial={‘author’: request.user})

• [forms.py]
class PostForm(forms.ModelForm):
author = forms.ModelChoiceField(queryset=User.objects.all(), required=True, widget=forms.HiddenInput())
class Meta:
model = Post
[views.py]
def home(request, template_name=’post/home.html’):
if request.method == ‘POST’:
post_form = PostForm(request.POST) if post_form.is_valid():
post_form.save()
else:
post_form = PostForm(initial={‘author’: request.user})

• [forms.py]
class PostForm(forms.ModelForm):
author = forms.HiddenInput() class Meta:
model = Post
[views.py]
def home(request, template_name=’post/home.html’):
if request.method == ‘POST’:
post_form = PostForm(request.POST) if post_form.is_valid():
post_form.save()
else:
post_form = PostForm(initial={‘author’: request.user})

• [forms.py]
class PostForm(forms.ModelForm):
author = forms.ModelChoiceField(queryset=User.objects.all(), required=True, widget=forms.HiddenInput())
class Meta:
model = Post
else:
else:
else:
[views.py]
def home(request, template_name=’post/home.html’):
if request.method == ‘POST’:
post_form = PostForm(request.POST) if post_form.is_valid():
post_form.save()
else:
post_form = PostForm()

39. Which of the following database is not supported by Django ORM?

• Mysql
• Postgresql
• Mongodb
• Oracle

40. Which of the following are built-in signal provided by Django?

• request_started
• pre_save
• m2m_changed
• pre_delete
• All of the above

41. Select all correct ways to add a message.
Note: There may be more than one right answer.

• messages.add_message(request, messages.INFO, ‘Hello world.’)
• messages.append(request, messages.INFO, ‘Hello world.’)
• messages.info(request, ‘Hello world.’)
• messages.success(request, ‘Hello world.’)

42. What kind of relation is defined between models A and B by invoking ForeignKey(A) in the class definition for model B?

• Many to one: each instance of A belongs to an instance of B
• One to many: each instance of B belongs to an instance of A
• One to one: each instance of A corresponds to a unique instance of B
• All of the above

43. Which of the following caching strategies can be implemented in Django?

• File system caching
• Local-memory caching
• Using Memcached
• Database caching
• All of the above

44. Which of the following caching strategies are supported in Django? (check any that apply)
Note: There may be more than one right answer.

• File sytem caching
• Proxy models
• Makemigrations
• In-memory caching

45. Which of the following is a possible usage of middlewares in Django?

• Session management
• CSRF Protection
• Content Gzipping
• All of the above

46. Which view functions is not correctly defined for the following urlconf?
from django.conf.urls.defaults import *
urlpatterns = patterns(‘news.views’, (r’^users/(?P\d+)/(?P\w+)’, ‘user_profile’),
)

• def user_profile(request, user_id, country):
user_id = user_id
country = country

• def user_profile(request,*args, **kwargs):
user_id = kwargs.get(‘user_id’)
country = kwargs.get(‘country’)

• def user_profile(request):
user_id = request.GET.post(‘user_id’)
country = request.GET.post(‘country’)

• def user_profile(request, user_id, **kwargs):
user_id = user_id
country = kwargs.get(‘country’)

47. For this template tag to work what does it do ?
{{ somevariable|cut:»0″ }}

• Copy “0” into somevariable
• Cut the variable to the clipboard
• Apply cut filter with value value = “0” and arg = somevariable
• Apply cut filter with value value = somevariable and arg = “0”

48. Which of the following is true about Form and Model Form?

• Forms created from forms.Form are manually configured.
• We use forms if the fields do not interact with model fields.
• If the form is going to be used to directly add or edit a Django model, we can use a ModelForm to avoid duplicating the model description.
• All of the above

49. How is the ManyToManyField represented in Django model form?

• CharField
• ModelChoiceField
• ModelMultipleChoiceField
• Checkbox

50. Which of the following is NOT used to represent ManyToManyField in django model form? Check all that apply.
Note: There may be more than one right answer.

• Charfield
• ModelChoiceField
• ModelMultipleChoiceField
• Checkbox

51. If an instance of a form is named ‘form’ then, which attribute of form instance holds all validated form data?

• form.is_valid
• form.cleaned_data
• form.clean_data
• form.data

52. Which form method binds the data in the URL and passed to the view?

• GET
• POST
• Both of the above
• None of the above

53. What is the correct way to specify the fields to use in a Model Form?

• Using fields attribute that specifies list of model fields in the form’s Meta class
• Using exclude attribute in the form’s Meta class
• Either 1 or 2
• None of the mentioned

54. How is it possible to create multiple forms on the same page?

• Use multiple Model Form
• Use formset that include multiple Model Forms
• Adjust the view to create a single form from all the Model Forms
• All of the above

55. What command line can be used to load data into Django?

• Admin.py loaddata
• Django-admin.py loaddata
• Djangoadmin loaddata
• Django-admin load data

56. Which types of users are allowed to login to the Django administration site?

• Staff users
• Super users
• Super users and staff users
• All users

57. Which of the following url patterns is used to register admin urls?

• url(r’^admin/’, include(admin.site.urls))
• url(r’^admin/’, include(admin.urls))
• url(r’^admin/’, include(admin))
• url(r’^admin/’, include(site.urls))

58. Which attribute is used to order the objects in django admin?

• order
• order_by
• ordering
• ordered

59. Which of the following will not register a model «Test» to Django admin?

• admin.site.register(Test)
• admin.site.register(Test, TestAdmin)
• admin(Test)
• @admin.register(Test)
class TestAdmin(admin.ModelAdmin):
pass

60. Which is the correct way to create a superuser from command line?

• python manage.py create superuser
• python manage.py createsuperuser
• python manage.py superuser create
• None of the mentioned

61. Which of the following is NOT used as a server for django in production?

• Mod_WSGI
• uWSGI
• Ansible
• Gunicorn

62. Which of the following is not True?

• The contenttypes application in django can track all of the models installed in your Django-powered project.
• The flatpages application in django lets you store simple “flat” HTML content in a database.
• The site’s framework is a holding place for the domain names and “verbose” names of your Django-powered sites.
• Django does not support Unicode data everywhere.

63. Which option is false in order to get a Queryset of all entries which were published in 2006?

• Entry.objects.all().filter(pub_date__year=2006)
• Entry.objects.get(pub_date__year=2006)
• Entry.objects.filter(pub_date__year=2006)

64. Which of the following is true for model field names?

• A field name cannot be a Python reserved word
• A field name cannot contain more than one underscore in a row
• Both of the above
• None of the above

65. What is the correct way to Abstract Model class?

• Add abstract=True in Meta class
• Add field name abstract=True
• Inherit from Abstract
• Override the abstract method

66. Which is the correct way to allow empty value in CharField?

• models.CharField(max_length=10)
• models.CharField(max_length=10, blank=True)
• models.CharField(max_length=10, null=True)
• models.CharField(max_length=10, blank=True, null=True)

67. What is the table name for a model named Choice in the application?

• choice_question
• questionchoice
• choicequestion
• question_choice

68. Which of the following statements is true about the QuerySet select_related() method?

• Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.
• Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.
• Returns a new QuerySet containing objects that do not match the given lookup parameters.
• None of the mentioned

69. What is the correct way to insert csrf token for forms in Django template?

• <form action=»» method=»post»>{% csrf_token %}
• {% csrf_token %}<form action=»» method=»post»>
• <form action=»» method=»post» {{csrf_token }}>
• <form action=»» method=»post»></form>{% csrf_token %}

70. Which decorators are used to restrict authentication of users?
Note: There may be more than one right answer.

• @permission_required
• @is_authenticated
• @user_passes_test
• @permissions
• @login_required

71. Session framework in Django will _____ data on server side?

• Pass
• Store
• Push
• Send

72. What does setting SESSION_COOKIE_SECURE = True do?

• Ensures cookie can be sent on HTTP connection only
• Ensures cookie can be sent on HTTPS connection only
• Ensures cookie can be sent on any connection
• Disables cookie

73. Which Django core function can be used to send an email?

• django.core.mail.send_mail
• django.core.email.send_mail
• django.core.mail.send_email
• None of the mentioned

74. Which of the following is not true about testing?

• Separate, blank databases are created for tests.
• The command used to run all unit tests is
./manage.py test —all
• Django’s unit tests use a Python standard library module called unittest
• We can use a custom name for the test database by specifying NAME in the TEST dictionary in settings.

75. What is the name of the command line tool that Django provides for managing a newly created project and its applications?

• pip
• manage.py
• django­admin.py
• easy_install

76. Using a template tag you tried to load a templatetag as in {% load poll_extras %} and it failed, what could be the problem ?

• You used the load in the wrong place of the page
• You passed the limit of template tags
• The app that contain the template tag is not in INSTALLED_APPS
• All of the above

77. Which template command makes a custom template tag/filter available in template?

• {% load %}
• {% include %}
• {% extend %}
• None of the mentioned

78. Which command runs all tests in a Django project?

• python manage.py runalltests
• python manage.py test
• python manage.py test —all
• None of the mentioned

79. Which of the following is true about generators?

• Generators must contain a previous statement
• Generators must contain a yield statement
• Generators must contain a next statement
• All of the above

80. What is true about the management command collectstatic?

• Takes all of the static files of your project and puts them in the folder specified in STATIC_ROOT so they can be served in production.
• Collect all static files and display the count.
• Both 1 and 2
• None of the mentioned

81. Which of the following is the correct way to check if a request uses HTTP POST method?

• request.is_post() == True
• request.METHOD == ‘post’
• request.method == ‘POST’
• HttpRequest.POST

82. Which of the following is not a layer in Django?

• Models
• Views
• Templates
• Controller
• None of the above

83. Django is written in

• Python
• C
• C++
• Python and C

84. Which of the following are valid built-in signals provided by Django?
Note: There may be more than one right answer.

• request_started
• pre_saved
• m2m_changed
• pre_modified

85. How can you access a variable in template which is passed from view? Suppose the variable name is object.

• {object}
• {{object}}
• {% object %}
• None of the mentioned

86. Which query includes a shirt with size 40?

• Shirt.objects.filter(size__gt=40)
• Shirt.objects.count(size__lte=40)
• Shirt.objects.filter(size==40)
• Both 1 and 2
• Both 2 and 3

87. How would you iterate through a list called my_list in template ?

• {% for x in my_list %} {% endfor %}
• {% items in my_list %} {% items %}
• {% iterate my_list as item %} {% enditerate %}
• {% while my_list %} {% endwhile %}

88. Which data structure is used to pass context values from views to template?

• List
• Tuple
• Dictionary
• Set

89. Which template tag is used to add another template to the current one?

• base
• lower
• join
• extend
• include

90. Which of following statement is true to get a Queryset of all Entries which were published before 2006?

• Entry.objects.filter(pub_date__year__lte=2006)
• Entry.objects.all().filter(pub_date__year__gte=2006)
• Entry.objects.get(pub_date__year__lt=2006)
• Entry.objects.get(pub_date__year__in=2006)

91. What is the exception raised when a duplicate value is used in unique field while inserting a record?

• ValidationError
• IntegrityError
• ObjectDoesNotExist
• FieldError

92. How would you check if a list my_list is empty or not in template ?

• {% if my_list %} {% endif %}
• {% if my_list|length > 0 %} {% endif %}
• Both 1 and 2
• None of the mentioned

93. What is the exception raised when for this query Entry.objects.filter(blog_id=4)?

• SyntaxError
• MultipleObjectsReturned
• MultipleModelReturned
• TypeError