Django MCQs

Django MCQs

These Django multiple-choice questions and their answers will help you strengthen your grip on the subject of Django. You can prepare for an upcoming exam or job interview with these Django MCQs.
So scroll down and start answering.

1: What is the command to start Django's built-in development server?

A.   manage.py --start

B.   manage.py startserver --dev

C.   manage.py run

D.   manage.py runserver

E.   manage.py --run

2: What is the definition of a Django Project?

A.   A collection of configuration files and individual apps that form a web site.

B.   A fork of the official Django repo.

C.   A web site that uses the Django framework.

D.   A specific piece of functionality that can be used in multiple Django apps.

3: What is the Django shortcut method to more easily render an html response?

A.   render_to_html

B.   response_render

C.   render

D.   render_to_response

4: What is the correct syntax for including a class based view in a URLconf?

A.   (r'^pattern/$', YourView.as_view()),

B.   (r'^pattern/$', YourView()),

C.   (r'^pattern/$', YourView),

D.   (r'^pattern/$', YourView.init()),

5: What is the definition of a good Django app?

A.   A good Django app is a fully functioning website that has 100% test coverage.

B.   A good Django app provides a small, specific piece of functionality that can be used in any number of Django projects.

C.   A good Django app is highly customized and cannot be used in multiple projects.

6: What is the purpose of settings.py?

A.   To sync the database schema

B.   To configure settings for an app

C.   To set the date and time on the server

D.   To configure settings for the Django project

7: Django is written using what programming language?

A.   Python

B.   Ruby

C.   PHP

D.   Javascript

E.   Java

8: What does a urls.py file do in Django?

A.   This file contains site deployment data such as server names and ports.

B.   It contains a site map of Django-approved URLs.

C.   You run this file when you get obscure 404 Not Found errors in your server logs.

D.   It contains URL matching patterns and their corresponding view methods.

E.   This file provides an up to date list of how-to URLs for learning Django more easily.

9: What is the command to run Django's development server on port 8080 on IP address 12.34.56.78?

A.   manage.py --dev 12.34.56.78:8080

B.   manage.py --run 12.34.56.78 8080

C.   manage.py runserver 12.34.56.78:8000

D.   manage.py run 12.34.56.78:8080

E.   manage.py runserver 12.34.56.78:8080

10: After you make a new 'app' in your existing Django project, how do you get Django to notice it?

A.   In settings.py, add the app to the PROJECT_APPS variable.

B.   In settings.py, add the new app to the INSTALLED_APPS variable.

C.   Run the `manage.py validate` command, and then start a new shell.

D.   No additional action is required, Django notices new apps automatically.

E.   Run the `manage.py syncdb` command.

11: What is the Django command to start a new app named 'users' in an existing project?

A.   manage.py startapp users

B.   manage.py --startapp users

C.   manage.py --newapp users

D.   manage.py newapp users

E.   manage.py start users

12: What is the most easiest, fastest, and most stable deployment choice in most cases with Django?

A.   AJP

B.   FastCGI

C.   SCGI

D.   mod_wsgi

13: How do you define a 'name' field in a Django model with a maximum length of 255 characters?

A.   model = CharField(max_length=255)

B.   name = models.CharField(max_len=255)

C.   name = models.CharField(max_length=255)

D.   name = model.StringField(max_length=auto)

E.   model.CharField(max_length=255)

14: What preferred method do you add to a Django model to get a better string representation of the model in the Django admin?

A.   to_s( self )

B.   __utf_8__

C.   __translate__

D.   __unicode__

15: How do you exclude a specific field from a ModelForm?

A.   Set the field to hidden

B.   Create a new Form, don't use a ModelForm

C.   You can not do this

D.   Use the exclude parameter in the Meta class in your form

16: What is ModelForm used for?

A.   To define a form based on an existing model

B.   To model an input form for a template

C.   To specify rules for correct form when writing Django code

17: Assuming you have a Django model named 'User', how do you define a foreign key field for this model in another model?

A.   user = models.ForeignKey(User)

B.   models.ForeignKey( self, User )

C.   user = models.IntegerKey(User)

D.   model = new ForeignKey(User)

18: Assuming you've imported the proper Django model file, how do you add a 'User' model to the Django admin?

A.   admin.site( self, User )

B.   users.site.register( Admin )

C.   admin.register( Users )

D.   user.site.register( Admin )

E.   admin.site.register( User )

19: What happens if MyObject.objects.get() is called with parameters that do not match an existing item in the database?

A.   The object is created and returned.

B.   The Http404 exception is raised.

C.   The DatabaseError exception is raised.

D.   The MyObject.DoesNotExist exception is raised.

20: How to make django timezone-aware?

A.   in views.py, import timezone

B.   In settings.py: USE_TZ=True

C.   in views.py, import tz

D.   In settings.py: USE_L10N=True

E.   in urls.py, import timezone

21: What is the command to start a new Django project called 'myproject'?

A.   django-admin.py --start myproject

B.   django.py --new myproject

C.   django.py startproject myproject

D.   django-admin.py startproject myproject

E.   django.py new myproject

22: In Django how would you retrieve all the 'User' records from a given database?

A.   User.all_records()

B.   Users.objects.all()

C.   User.objects

D.   User.object.all()

E.   User.objects.all()

23: A set of helpful applications to use within your Django projects is included in the official distribution. This module is called what?

A.   django.helpers

B.   django.extras

C.   django.contrib

D.   django.utilities

E.   django.ponies

24: What does the Django command `manage.py shell` do?

A.   Starts a command line in whatever $SHELL your environment uses.

B.   Starts a Django command prompt with your Python environment pre-loaded.

C.   Loads a Python command prompt you can use to sync your database schema remotely.

D.   Loads a special Pythonic version of the Bash shell.

E.   Starts a Python command prompt with your Django environment pre-loaded.

25: How can you define additional behavior and characteristics of a Django class?

A.   def __init__():

B.   def Meta():

C.   class Meta:

D.   def setUp():

E.   class __init__:

26: Where is pre_save signal in Django

A.   There is no pre_save signal

B.   from django.db.models import pre_save

C.   from django.db.models.signal import pre_save

D.   from django.db.models.signals import pre_save

27: What is Dijit?

A.   Dijit is Dojo's git interface.

B.   Dijit is Dojo’s UI Library.

C.   Dijit is Dojo's AMD loader.

D.   Dijit is Dojo's interface to the jQuery effects functions.

E.   Dijit is Dojo's math library.

28: What does the Django command `manage.py validate` do?

A.   Checks for errors in your models.

B.   Checks for errors in your views.

C.   Checks for errors in your settings.py file.

D.   Checks for errors in your templates.

E.   Checks for errors in your controllers.

29: What is the correct way to include django's admin urls? from django.contrib import admin') from django.conf.urls import patterns, include, url urlpatterns = patterns('', ______________________ )

A.   url(r'^admin/', include(admin.site.urls) ),

B.   url(r'^admin/', admin.as_view(), name='admin ),

C.   url(r'^admin/', include(admin) ),

D.   url(r'^admin/', admin.urls ),

E.   admin.autodiscover()

30: What is the purpose of the STATIC_ROOT setting?

A.   Defines the URL prefix where static files will be served from .

B.   Defines the location where all static files will be copied by the 'collectstatic' management command, to be served by the production webserver.

C.   Defines the location for serving user uploaded files.

D.   A project's static assets should be stored here to be served by the development server.

31: Given the Python data: mydata = [ [ 0, 'Fred' ], [ 1, 'Wilma' ] ] How do you access the data in a Django template?

A.   {% for d in mydata -%} <p><a href="/users/{{ d.0 }}/">{{ d.1 }}</a></p> {% end -%}

B.   {% for d in mydata %} <p><a href="/users/{{ d.0 }}/">{{ d.1 }}</a></p> {% endfor %}

C.   {% mydata.each |d| %} <p><a href="/users/{{ d.1 }}/">{{ d.2 }}</a></p> {% end %}

D.   {{ for d in mydata }} <p><a href="/users/{{ d[0] }}/">{{ d[1] }}</a></p> {{ endfor }}

E.   {% for d in mydata %} <p><a href="/users/{% d.0 %}/">{% d.1 %}</a></p> {% endfor %}

32: Given an IntegerField named 'widgets' in the Django model 'User' , how do you calculate the average number of widgets per user?

A.   Widget.objects.all().aggregate( Avg( 'users' ) )

B.   User.objects.all().aggregate( Avg( 'widgets' ) )

C.   User.objects.avg( 'widgets' )

D.   User.objects.all().aggregate( Sum( 'widgets' ) )

E.   User.all().aggregate( Avg( 'widgets' ) ).count()

33: Given a model named 'User' that contains a DateTime field named 'last_login', how do you query for users that have never logged in?

A.   User.objects.filter( last_login__isnull=True )

B.   User.objects.filter( last_login=Null )

C.   User.objects.filter( last_login=Never )

D.   User.objects.filter( last_login__null=True )

E.   User.objects.filter( last_login__isnull=False )

34: What is the Django command to view a database schema of an existing (or legacy) database?

A.   django-admin.py inspect

B.   manage.py inspectdb

C.   manage.py inspect

D.   manage.py legacydb

E.   django-admin.py schemadump

35: Given a model named 'User' that contains a field named 'email', how do you perform a case-insensitive exact match for the email 'fred@aol.com'?

A.   User.objects.filter( email__iexact='fred@aol.com' )

B.   User.objects.filter( email__matches='fred@aol.com' )

C.   User.objects.filter( email__exact='fred@aol.com' )

D.   User.objects.filter( email__contains='fred@aol.com' )

E.   User.objects.filter( email__icontains='fred@aol.com' )

36: What command compile Django's translation files?

A.   ./manage.py compilemessages

B.   ./manage.py compiletranslation

C.   ./manage.py translate_files

D.   ./manage.py compilei18n

E.   ./manage.py i18n_update

37: Given a form with field foo, what should the validation method for this field be called?

A.   foo_clean

B.   validate_foo

C.   clean_foo

D.   foo_is_valid

38: You have created a Form class and wish to provide custom logic for validating the input in the "foo" field. What would you name your custom validation method?

A.   foo_clean

B.   clean_foo

C.   clean_foo_field

D.   sanitize_foo

E.   validate_foo

39: What is the Django command to retrieve the first 10 'User' records from your database sorted by name descending?

A.   User.objects.all().order('-name')[:10]

B.   User.all().order_by('-name')[10:]

C.   User.objects.all().order('-name')[10:]

D.   User.objects.all().order_by('-name')[:10]

E.   User.objects.all().order_by('name')[:10]

40: How to create a DateTimeField named created and filled in only on the creation with the current time?

A.   created = models.DateTimeField(auto_now=True)

B.   created = models.DateTimeField(default=datetime.datetime.now())

C.   created = models.CreationTimeField()

D.   created = models.DateTimeField(auto_now_add=True, auto_now=True)

E.   created = models.DateTimeField(auto_now_add=True)

41: You can handle multiple Django forms with what keyword argument when creating forms?

A.   suffix

B.   prefix

C.   name

D.   infix

42: When customizing validation in a Form subclass named MyForm, how do you add an error message that is displayed as a form-wide error?

A.   Raise ValidationError in MyForm.clean_<fieldname>()

B.   Raise ValidationError in MyForm.clean()

C.   Add the error to MyForm.errors in MyForm.clean()

D.   Add the error to MyForm._errors in MyForm.clean()

43: What command do you use to alter the fields Django displays for a given model in the Django admin ListView?

A.   fields_display

B.   list_filter

C.   fields_list

D.   auto_list_fields

E.   list_display

44: What is the command used to print the CREATE TABLE SQL statements for the given app name?

A.   django-admin.py dumpdata myapp

B.   ./manage.py schema myapp

C.   ./manage.py sql myapp

D.   ./manage.py showschema myapp

E.   ./manage.py showsql myapp

45: In settings.py, when DEBUG is set to ________, Django will email unhandled exceptional conditions.

A.   True

B.   Always

C.   1

D.   Never

E.   False

46: You have a Form defined with "password" and "confirm_password" fields. In what method of the "form" object would you validate that the values supplied in these fields match?

A.   form.clean_password

B.   form.clean_confirm_password

C.   form.sanitize_data

D.   form.clean

E.   form.validate

47: How do you create a recursive relationship in a model class named 'Company' in Django?

A.   models.ForeignKey('self')

B.   models.ForeignKey('Company')

C.   models.ForeignKey('me')

D.   models.ForeignKey(Company)

48: Which class is a model field representing a path to a server-based image file?

A.   django.db.models.fields.files.ImageFieldFile

B.   django.db.models.fields.files.ImageFile

C.   django.db.models.fields.files.ImageFileField

D.   django.db.models.fields.files.ImageFileDescriptor

E.   django.db.models.fields.files.ImageField

49: Which of these can be used to retrieve a setting from the settings module, and provide a default if the setting is not defined?

A.   settings.get("SETTING_NAME", default_value)

B.   getattr("SETTING_NAME", settings, default=default_value)

C.   get_setting("SETTING_NAME", default=default_value)

D.   getattr(settings, "SETTING_NAME", default_value)

50: The Benevolent Dictators for Life of the Django Project are:

A.   Guido van Rossum and Linus Torvalds

B.   Ian Bicking and Jannis Leidel

C.   and Armando De La Veloper

D.   Eric S. Raymond and Larry Wall

E.   Jacob Kaplan-Moss and Adrian Holovaty

51: The django.contrib.contenttypes application provides

A.   mimetypes used for returning http responses

B.   a generic interface for working with models

C.   functionality for working with varied file formats

D.   none of the others

52: In your django template, if you need to get the content of the block from the django parent template, what do you need to add? {% block my_block %} ___________ {% endblock %}

A.   {{ extends block }}

B.   {{ block.super }}

C.   {% block.super %}

D.   super (block, self)__init__()

E.   {% super %}

53: Which type of custom template tag returns a string?

A.   assignment_tag

B.   simple_tag

C.   inclusion_tag

D.   string_tag

54: How to set a default order by in your Django model ? YourModel.objects.all() will be ordered by default without calling order_by() method

A.   Using META default_order attribute

B.   Using META order_by attribute

C.   Using META default_order_by attribute

D.   Using META order attribute

E.   Using META ordering attribute

55: A model's "full_clean()" method is called automatically when you call your model's "save()" method.

A.   True

B.   False

56: Given a model named 'User' that contains a CharField 'name', how do you query for users whose name starts with 'Fred' or 'Bob'?

A.   User.objects.filter( name__iregex=r'^(fred|bob)$' )

B.   User.objects.filter( name__iregex=r'^(fred|bob).+' )

C.   User.objects.filter( name_iregex=r'^(fred|bob)+' )

D.   User.objects.filter( name__like=r'^(fred|bob)*' )

E.   User.objects.filter( name__regex=r'^(fred|bob)+' )

57: How would you perform a lookup on a model against a database aside from the default?

A.   Model.objects.using('other').all()

B.   Model.objects.all(using='other')

C.   Model.objects.all(database='other')

D.   Model.objects.database('other').all()

58: Which model field type does NOT exist in Django?

A.   CommaSeparatedIntegerField

B.   IPAddressField

C.   SmallIntegerField

D.   SlugField

E.   LargeIntegerField

59: How would you create a ForeignKey from a model named Transaction, to a model named Product, with no reverse relation?

A.   class Transaction(models.Model): product = models.ForeignKey(Product, related_name=None)

B.   class Transaction(models.Model): product = models.ForeignKey(Product, related_name='+')

C.   class Transaction(models.Model): product = models.ForeignKey(Product, related_name=False)

D.   class Transaction(models.Model): product = models.ForeignKey(Product, related_name='')

60: What datetime formatting would you apply in a template to display the following: 2013/03/20 8:00:06 AM ?

A.   Y/m/d g:i:s A

B.   Y-m-d H:m:s

C.   m/d/Y h:m:s

D.   Y/m/d H:i

E.   Y/m/d H:i:s A

61: What is the name of the Django decorator that hides sensitive info from error reports?

A.   @secret_fields

B.   @sensitive_variables

C.   @secret_variables

D.   @sensitive_fields

E.   @hide_fields

62: By using django.contrib.humanize, you can use the following filter in your template to display the number 3 as three.

A.   intword

B.   intcomma

C.   apnumber

D.   naturaltime

E.   ordinal

63:

How is the ManyToManyField represented in Django model form?

A.   CharField

B.   ModelChoiceField

C.   ModelMultipleChoiceField

D.   Checkbox

64:

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.

A.   Charfield

B.   ModelChoiceField

C.   ModelMultipleChoiceField

D.   Checkbox 

65:

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

A.   Using fields attribute that specifies list of model fields in the form’s Meta class

B.   Using exclude attribute in the form’s Meta class

C.   Either 1 or 2

D.   None of the mentioned

66:

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

    pass

A.   HttpResponseNotAllowed

B.   HttpResponseForbidden

C.   HttpResponseBadRequest

D.   No exception will be raised

67:

What is the correct way to insert csrf token for forms in django template?

A.   form action="" method="post">{% csrf_token %}

B.   {% csrf_token %}

C.  

D.   {% csrf_token %}

68:

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

A.   django.core.mail.send_mail

B.   django.core.email.send_mail

C.   django.core.mail.send_email

D.   None of the mentioned

69:

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

A.   You used the load in the wrong place of the page

B.   You passed the limit of template tags

C.   The app that contain the template tag is not in INSTALLED_APPS

D.   All of the above

70:

Which of the following are correct ways to add a message?

A.   messages.add_message(request, messages.INFO, 'Hello world.')

B.   messages.add(request, messages.INFO, 'Hello world.')

C.   messages.info(request, 'Hello world.')

D.   messages.success(request, 'Hello world.') 

A.   Ensures cookie can be sent on HTTP connection only

B.   Ensures cookie can be sent on HTTPS connection only

C.   Ensures cookie can be sent on any connection

D.   Disables cookie

72:

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

A.   Programming

B.   Framework

C.   API

D.   Library

73:

How can you set up static files in Django?

A.   set STATIC_ROOT in settings.py

B.   run manage.py collectsatic

C.   set up a Static Files entry on the PythonAnywhere web tab

D.   All of the above

74:

Which is the correct way to allow empty value in Integer Field?

A.   models.IntegerField()

B.   models.IntegerField(blank=True)

C.   models.IntegerField(null=True)

D.   models.IntegerField(blank=True, null=True)

75:

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

A.   ValidationError

B.   IntegrityError

C.   ObjectDoesNotExist

D.   FieldError

76:

Which of the following features are supported by Django?

A.   Development Environment

B.   Administration GUI

C.   Multilingual system

D.   Object Relational Mapping (ORM)

E.   All of the above 

77:

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

A.   by using the function ugettext()

B.   by using the function ugettext_lazy()

C.   Both of the above

D.   None of the above

78:

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

A.   File system caching

B.   Local-memory caching

C.   Using Memcached

D.   Database caching

E.   All of the above

79:

Which of the following caching strategies are supported in Django? (check any that apply)

Note: There may be more than one right answer.

A.   File sytem caching

B.   Proxy models

C.   Makemigrations

D.   In-memory caching 

80:

What is the full form of FBV and CBV?

A.   Function Based Views & Class Based Views

B.   Function Behind Views & Class Behind Views

C.   Function Before Views & Class Before Views

D.   None of the mentioned

81:

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

A.   Mod_WSGI

B.   uWSGI

C.   Ansible

D.   Gunicorn

82:

Which of the following is true about generators?

A.   Generators must contain a previous statement

B.   Generators must contain a yield statement

C.   Generators must contain a next statement

D.   All of the above

83:

Which decorators are used to restrict authentication of users?

Note: There may be more than one right answer.

A.   @permission_required

B.   @is_authenticated

C.   @user_passes_test

D.   @permissions

E.   @login_required 

84:

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

A.   python manage.py create superuser

B.   python manage.py createsuperuser

C.   python manage.py superuser create

D.   None of the mentioned

85:

Which of the following methods is not used in django ListView?

A.   get_object

B.   get_context_data

C.   get_queryset

D.   get

86:

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

A.   order

B.   order_by

C.   ordering

D.   ordered

87:

Which query gives the count of vehicles that are private?

A.   Vehicle.objects.filter(private=True).count()

B.   Vehicle.objects.count(private=True)

C.   Vehicle.objects.filter(private=True).aggregate(Count(‘id’))

D.   Both 1 and 2

E.   Both 1 and 3

88:

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

A.   List

B.   Tuple

C.   Dictionary

D.   Set

E.   String

89:

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

A.   {% for x in my_list %} {% endfor %}

B.   {% items in my_list %} {% items %}

C.   {% iterate my_list as item %} {% enditerate %}

D.   {% while my_list %} {% endwhile %}

E.   {% cycle my_list as item %}

90:

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

A.   base

B.   lower

C.   join

D.   extend

E.   include

91:

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

A.   HttpResponseNotModified

B.   HttpResponseRedirect

C.   HttpResponseForbidden

D.   HttpResponseServerError

92:

Which of the following is not a layer in Django?

A.   Models

B.   Views

C.   Templates

D.   Controller

E.   None of the above

93:

Which of the following is not True?

A.   The contenttypes application in django can track all of the models installed in your Django-powered project.

B.   The flatpages application in django lets you store simple “flat” HTML content in a database.

C.   The sites framework is a holding place for the domain names and “verbose” names of your Django-powered sites.

D.   Django does not support Unicode data everywhere.

94:

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

A.   Many to one: Many instances of B can have one instance of A

B.   One to many: One instance of B can have many instances of A

C.   One to one: One instance of B must have a unique instance of A and vice versa

D.   All of the above

95:

Which command runs all test in a django project?

A.   python manage.py runalltests

B.   python manage.py test

C.   python manage.py test --all

D.   None of the mentioned

96:

Which of the following is not true about testing?

A.   Separate, blank databases are created for tests.

B.   The command used to run all unit tests is ./manage.py test --all

C.   Django’s unit tests use a Python standard library module called unittest

D.   We can use a custom name for the test database by specifying NAME in the TEST dictionary in settings.

97:

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

A.   pip

B.   manage.py

C.   django¬admin.py

D.   easy_install

98:

What is true about the management command collectstatic?

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

B.   Collect all static files and display the count.

C.   Both 1 and 2

D.   None of the mentioned

99:

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

A.   url(r'^admin/', include(admin.site.urls))

B.   url(r'^admin/', include(admin.urls))

C.   url(r'^admin/', include(admin))

D.   url(r'^admin/', include(site.urls))

100:

Which of the following are determined by Django using field class types?

A.   The database column type

B.   The default HTML widget to avail while rendering a form field

C.   Makemigrations

D.   All of the above