Top 100 Django Interview Questions
What is the command to start Django’s built-in development server?
A. manage.py runserver
B. manage.py –start
C. manage.py run
D. manage.py startserver –dev
E. manage.py –run
Ans: A
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=Null )
B. User.objects.filter( last_login__null=True )
C. User.objects.filter( last_login__isnull=False )
D. User.objects.filter( last_login__isnull=True )
E. User.objects.filter( last_login=Never )
Ans: D
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. Starts a Python command prompt with your Django environment pre-loaded.
D. Loads a special Pythonic version of the Bash shell.
E. Loads a Python command prompt you can use to sync your database schema remotely.
Ans: C
Assuming you’ve imported the proper Django model file, how do you add a ‘User’ model to the Django admin?
A. admin.register( Users )
B. admin.site( self, User )
C. user.site.register( Admin )
D. users.site.register( Admin )
E. admin.site.register( User )
Ans: E
What is the Django command to start a new app named ‘users’ in an existing project?
A. manage.py –newapp users
B. manage.py newapp users
C. manage.py –startapp users
D. manage.py startapp users
E. manage.py start users
Ans: D
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. It contains URL matching patterns and their corresponding view methods.
D. You run this file when you get obscure 404 Not Found errors in your server logs.
E. This file provides an up to date list of how-to URLs for learning Django more easily.
Ans: C
What is the command to run Django’s development server on port 8080 on IP address 12.34.56.78?
A. manage.py –run 12.34.56.78 8080
B. manage.py –dev 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
Ans: E
Django is written using what programming language?
A. PHP
B. Ruby
C. Javascript
D. Java
E. Python
Ans: E
After you make a new ‘app’ in your existing Django project, how do you get Django to notice it?
A. No additional action is required, Django notices new apps automatically.
B. Run the `manage.py validate` command, and then start a new shell.
C. Run the `manage.py syncdb` command.
D. In settings.py, add the app to the PROJECT_APPS variable.
E. In settings.py, add the new app to the INSTALLED_APPS variable.
Ans: E
What is the purpose of settings.py?
A. To configure settings for the Django project
B. To configure settings for an app
C. To set the date and time on the server
D. To sync the database schema
Ans: A
How do you define a ‘name’ field in a Django model with a maximum length of 255 characters?
A. name = models.CharField(max_len=255)
B. model.CharField(max_length=255)
C. name = models.CharField(max_length=255)
D. model = CharField(max_length=255)
E. name = model.StringField(max_length=auto)
Ans: C
What is the definition of a good Django app?
A. A good Django app provides a small, specific piece of functionality that can be used in any number of Django projects.
B. A good Django app is a fully functioning website that has 100% test coverage.
C. A good Django app is highly customized and cannot be used in multiple projects.
Ans: A
What is the most easiest, fastest, and most stable deployment choice in most cases with Django?
A. FastCGI
B. mod_wsgi
C. SCGI
D. AJP
Ans: B
How do you exclude a specific field from a ModelForm?
A. Create a new Form, don’t use a ModelForm
B. Use the exclude parameter in the Meta class in your form
C. Set the field to hidden
D. You can not do this
Ans: B
Assuming you have a Django model named ‘User’, how do you define a foreign key field for this model in another model?
A. model = new ForeignKey(User)
B. user = models.IntegerKey(User)
C. user = models.ForeignKey(User)
D. models.ForeignKey( self, User )
Ans: C
What preferred method do you add to a Django model to get a better string representation of the model in the Django admin?
A. __unicode__
B. to_s( self )
C. __translate__
D. __utf_8__
Ans: A
What is ModelForm used for?
A. To model an input form for a template
B. To specify rules for correct form when writing Django code
C. To define a form based on an existing model
Ans: C
What happens if MyObject.objects.get() is called with parameters that do not match an existing item in the database?
A. The Http404 exception is raised.
B. The DatabaseError exception is raised.
C. The MyObject.DoesNotExist exception is raised.
D. The object is created and returned.
Ans: C
A set of helpful applications to use within your Django projects is included in the official distribution. This module is called what?
A. django.extras
B. django.helpers
C. django.utilities
D. django.ponies
E. django.contrib
Ans: E
What is the correct syntax for including a class based view in a URLconf?
A. (r’^pattern/$’, YourView.as_view()),
B. (r’^pattern/$’, YourView.init()),
C. (r’^pattern/$’, YourView),
D. (r’^pattern/$’, YourView()),
Ans: A
What is the command to start a new Django project called ‘myproject’?
A. django-admin.py startproject myproject
B. django-admin.py –start myproject
C. django.py startproject myproject
D. django.py –new myproject
E. django.py new myproject
Ans: A
How to make django timezone-aware?
A. In settings.py: USE_L10N=True
B. in views.py, import timezone
C. in views.py, import tz
D. in urls.py, import timezone
E. In settings.py: USE_TZ=True
Ans: E
In Django how would you retrieve all the ‘User’ records from a given database?
A. User.objects.all()
B. Users.objects.all()
C. User.all_records()
D. User.object.all()
E. User.objects
Ans: A
How can you define additional behavior and characteristics of a Django class?
A. def setUp():
B. class Meta:
C. class __init__:
D. def Meta():
E. def __init__():
Ans: B
What is the Django shortcut method to more easily render an html response?
A. render_to_html
B. render_to_response
C. response_render
D. render
Ans: B
What does the Django command `manage.py validate` do?
A. Checks for errors in your views.
B. Checks for errors in your templates.
C. Checks for errors in your controllers.
D. Checks for errors in your models.
E. Checks for errors in your settings.py file.
Ans: D
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/’, admin.as_view(), name=’admin ),
B. url(r’^admin/’, include(admin) ),
C. url(r’^admin/’, include(admin.site.urls) ),
D. url(r’^admin/’, admin.urls ),
E. admin.autodiscover()
Ans: C
Where is pre_save signal in Django
A. from django.db.models import pre_save
B. from django.db.models.signals import pre_save
C. There is no pre_save signal
D. from django.db.models.signal import pre_save
Ans: B
Given the Python data: mydata = [ [ 0, ‘Fred’ ], [ 1, ‘Wilma’ ] ] How do you access the data in a Django template?
A. {% for d in mydata %}
{% d.1 %}
{% endfor %}
B. {% for d in mydata -%}
{{ d.1 }}
{% end -%}
C. {% for d in mydata %}
{{ d.1 }}
{% endfor %}
D. {{ for d in mydata }}
{{ d[1] }}
{{ endfor }}
E. {% mydata.each |d| %}
{{ d.2 }}
{% end %}
Ans: C
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. A project’s static assets should be stored here to be served by the development server.
D. Defines the location for serving user uploaded files.
Ans: B
How to create a DateTimeField named created and filled in only on the creation with the current time?
A. created = models.CreationTimeField()
B. created = models.DateTimeField(default=datetime.datetime.now())
C. created = models.DateTimeField(auto_now_add=True, auto_now=True)
D. created = models.DateTimeField(auto_now=True)
E. created = models.DateTimeField(auto_now_add=True)
Ans: E
Given an IntegerField named ‘widgets’ in the Django model ‘User’ , how do you calculate the average number of widgets per user?
A. User.objects.avg( ‘widgets’ )
B. Widget.objects.all().aggregate( Avg( ‘users’ ) )
C. User.all().aggregate( Avg( ‘widgets’ ) ).count()
D. User.objects.all().aggregate( Avg( ‘widgets’ ) )
E. User.objects.all().aggregate( Sum( ‘widgets’ ) )
Ans: D
What is the Django command to view a database schema of an existing (or legacy) database?
A. manage.py legacydb
B. django-admin.py schemadump
C. manage.py inspect
D. manage.py inspectdb
E. django-admin.py inspect
Ans: D
What is the Django command to retrieve the first 10 ‘User’ records from your database sorted by name descending?
A. User.all().order_by(‘-name’)[10:]
B. User.objects.all().order(‘-name’)[:10]
C. User.objects.all().order_by(‘-name’)[:10]
D. User.objects.all().order_by(‘name’)[:10]
E. User.objects.all().order(‘-name’)[10:]
Ans: C
What is the definition of a Django Project?
A. A specific piece of functionality that can be used in multiple Django apps.
B. A fork of the official Django repo.
C. A web site that uses the Django framework.
D. A collection of configuration files and individual apps that form a web site.
Ans: D
Given a model named ‘User’ that contains a field named ’email’, how do you perform a case-insensitive exact match for the email ‘[email protected]’?
A. User.objects.filter( email__icontains=’[email protected]’ )
B. User.objects.filter( email__iexact=’[email protected]’ )
C. User.objects.filter( email__contains=’[email protected]’ )
D. User.objects.filter( email__exact=’[email protected]’ )
E. User.objects.filter( email__matches=’[email protected]’ )
Ans: B
Given a form with field foo, what should the validation method for this field be called?
A. foo_clean
B. foo_is_valid
C. clean_foo
D. validate_foo
Ans: C
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. clean_foo
B. foo_clean
C. clean_foo_field
D. sanitize_foo
E. validate_foo
Ans: A
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. Add the error to MyForm.errors in MyForm.clean()
B. Raise ValidationError in MyForm.clean_()
C. Raise ValidationError in MyForm.clean()
D. Add the error to MyForm._errors in MyForm.clean()
Ans: C
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.ImageField
D. django.db.models.fields.files.ImageFileField
E. django.db.models.fields.files.ImageFileDescriptor
Ans: C
In settings.py, when DEBUG is set to ________, Django will email unhandled exceptional conditions.
A. False
B. 1
C. Always
D. True
E. Never
Ans: A
What is the command used to print the CREATE TABLE SQL statements for the given app name?
A. ./manage.py sql myapp
B. ./manage.py schema myapp
C. ./manage.py showsql myapp
D. django-admin.py dumpdata myapp
E. ./manage.py showschema myapp
Ans: A
How do you create a recursive relationship in a model class named ‘Company’ in Django?
A. models.ForeignKey(Company)
B. models.ForeignKey(‘self’)
C. models.ForeignKey(‘me’)
D. models.ForeignKey(‘Company’)
Ans: B
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_confirm_password
B. form.clean
C. form.validate
D. form.sanitize_data
E. form.clean_password
Ans: B
What command do you use to alter the fields Django displays for a given model in the Django admin ListView?
A. auto_list_fields
B. list_filter
C. list_display
D. fields_display
E. fields_list
Ans: C
You can handle multiple Django forms with what keyword argument when creating forms?
A. suffix
B. prefix
C. name
D. infix
Ans: B
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. get_setting(“SETTING_NAME”, default=default_value)
B. getattr(“SETTING_NAME”, settings, default=default_value)
C. settings.get(“SETTING_NAME”, default_value)
D. getattr(settings, “SETTING_NAME”, default_value)
Ans: D
The Benevolent Dictators for Life of the Django Project are:
A. Ian Bicking and Jannis Leidel
B. Jacob Kaplan-Moss and Adrian Holovaty
C. and Armando De La Veloper
D. Guido van Rossum and Linus Torvalds
E. Eric S. Raymond and Larry Wall
Ans: B
The django.contrib.contenttypes application provides
A. functionality for working with varied file formats
B. mimetypes used for returning http responses
C. a generic interface for working with models
D. none of the others
Ans: C
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. {% super %}
B. {{ extends block }}
C. super (block, self)__init__()
D. {{ block.super }}
E. {% block.super %}
Ans: D
Which type of custom template tag returns a string?
A. inclusion_tag
B. assignment_tag
C. string_tag
D. simple_tag
Ans: D
What command compile Django’s translation files?
A. ./manage.py translate_files
B. ./manage.py compilei18n
C. ./manage.py compilemessages
D. ./manage.py i18n_update
E. ./manage.py compiletranslation
Ans: C
A model’s “full_clean()” method is called automatically when you call your model’s “save()” method.
A. True
B. False
Ans: B
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.database(‘other’).all()
C. Model.objects.all(using=’other’)
D. Model.objects.all(database=’other’)
Ans: A
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__regex=r’^(fred|bob)+’ )
B. User.objects.filter( name_iregex=r’^(fred|bob)+’ )
C. User.objects.filter( name__like=r’^(fred|bob)*’ )
D. User.objects.filter( name__iregex=r’^(fred|bob).+’ )
E. User.objects.filter( name__iregex=r’^(fred|bob)$’ )
Ans: D
Which model field type does NOT exist in Django?
A. CommaSeparatedIntegerField
B. LargeIntegerField
C. IPAddressField
D. SlugField
E. SmallIntegerField
Ans: B
What datetime formatting would you apply in a template to display the following: 2013/03/20 8:00:06 AM ?
A. Y/m/d H:i
B. m/d/Y h:m:s
C. Y/m/d g:i:s A
D. Y-m-d H:m:s
E. Y/m/d H:i:s A
Ans: C
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=”)
Ans: B
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 attribute
C. Using META order_by attribute
D. Using META ordering attribute
E. Using META default_order_by attribute
Ans: D
What is the name of the Django decorator that hides sensitive info from error reports?
A. @secret_variables
B. @sensitive_variables
C. @hide_fields
D. @secret_fields
E. @sensitive_fields
Ans: B
By using django.contrib.humanize, you can use the following filter in your template to display the number 3 as three.
A. apnumber
B. intcomma
C. intword
D. ordinal
E. naturaltime
Ans: A