Django Technical Interview Questions

Updated

Table of Contents

The technical interview is a dreaded but necessary part of landing a programming job, in this case, for web development with Django. It's important to understand that you are already in a good position if you land an in-person interview with a company. Most companies use screening filters such as online assessments and take-home projects because employee time is valuable, so it is only after you have passed these steps that they will invite you for an in-person interview.

The interview is designed to test two things: how much Django do you know, and what would you be like as an employee? A good interviewer is not trying to trick or make you feel stupid. They'll come in with a list of questions of increasing difficulty to gauge your proficiency, but nobody can answer every question on the spot. That's to be expected. It's also true that Django covers such a wide area of features that no one can master every area. What's more important is to have a solid basic understanding and be open and honest about what you don't know. You should also express a willingness to learn and explain how you might fill in any gaps in your knowledge.

In your responses, try to avoid yes or no answers. Take every question as an opportunity to talk about what you do know. The best interviews are more like casual conversations similar to those co-workers would have. They discuss projects and how to implement them, design choices, tricky features, and so on. The more you prepare up front, the greater the likelihood your interview will quickly skip into this phase rather than simple questions and answers.

Sections

Beginner Django Questions

Most interviewers will start with some ice-breaker questions to help you calm your nerves before moving on to the more technical questions. These are generally easier questions that can be answered quickly but are a good chance to demonstrate what you know.

1. What is Django?

Django is an open-source web framework written in Python. It was first released in 2005 and named after the jazz guitarist Django Reinhardt. Django is used by some of the world's most popular websites, including Instagram, YouTube, Dropbox, Mozilla, Bitbucket, Udemy, and more. The non-profit Django Software Foundation maintains the framework. Bonus points if you can compare Django to other web frameworks like Ruby on Rails, Laravel in PHP, or Flask.

2. What are the major differences between Django and Flask?

Both are popular Python web frameworks used to create web applications, but each adopts a different approach. Django is a full-stack "batteries-included" web framework with everything you need to quickly build a web application, including user accounts, ORM, templating, security, built-in admin, and more. In contrast, Flask is a much more lightweight microframework, meaning it is more flexible and easy to customize, yet that also means relying on third-party packages for core features such as an ORM, user accounts, forms, and so on. Check out our in-depth article to learn more about Flask vs Django.

3. What are some built-in "batteries" that Django includes by default?

There are many ways to answer this question, but the major features would include the ORM (Object-Relational Mapper), Admin, URL routing, Django Templating Language, migrations framework, authentication framework, forms, testing library, Internationalization, built-in security, generic class-based views, and more.

4. What is the MTV (Model-Template-View) architecture of Django?

Traditionally, many web frameworks use an MVC (Model-View-Controller) approach, but Django's approach is slightly different. In Django, the Model handles the database and defines the structure of stored data. The Template manages the presentation layer of HTML, CSS, and JavaScript. The View is the business logic layer that retrieves data from the Model and passes it to the template.

5. What is the difference between a Project and an App?

In Django, a single project can contain many different apps. For example, if we were to build a clone of Instagram, there would be a single project and various apps focusing on discrete functionality such as authentication, posts, followers, image uploading, and so on.

6. How do you create a new Django project?

You use the command django-admin startproject <name> to set up a Django project directory with basic configuration settings. Extra credit if you mention that it is possible to add a period, ., to the end of the command to create only one main directory.

7. How do you start a new app?

With the command python manage.py startapp <name>.

8. How do you run the local development server?

With the command python manage.py runserver.

9. What do the makemigrations and migrate commands do?

makemigrations configures and creates a basic migrations file that preps the database for changes, while migrate enforces the changes and applies them to the database.

10. What is the Django admin?

The admin is a graphical user interface that allows for CRUD operations, permissions, and more. It is built into Django but can be customized and extended as needed. To access it, you must create a superuser account with the command python manage.py createsuperuser and then go to /admin to log in.

11. What is an ORM? How does Django's ORM work?

Django's ORM (Object-Relational Mapper) is an abstraction that allows developers to interact with their database by writing Python code rather than raw SQL. It also allows Django to support multiple types of databases: SQLite, PostgreSQL, MariaDB, MySQL, and Oracle. A developer can access the ORM

12. What is a Django model?

A Django model is a Python class that defines the structure and representation of data within a single database table. Each attribute of the class corresponds to a field in the database and specifies the type of data permitted (integer, character, date, etc.).

13. What is a Django view?

A Django view is a Python function or class that takes a web request and returns a web response. It handles the business logic of connecting models and templates. There are three main types of views: function-based, class-based, and generic class-based. Bonus points if you can list some generic class-based views such as TemplateView, RedirectView, ListView, DetailView, FormView, CreateView, UpdateView, or DeleteView.

14. How does the URL dispatcher work in Django?

The URL dispatcher in Django matches incoming web requests to the appropriate view based on the requested URL. A urls.py file, typically located in the project-level directory and within each app, uses regular expressions and path converters to match URL paths. Using named URLs makes it easier to refer to a URL path unambiguously from anywhere in your code, most notably in templates. It is especially useful for reversing URL patterns dynamically using the reverse() function. Django returns a 404 by default if no URL pattern is found for an incoming request.

15. What is a Django template?

Templates are Django's presentation layer and allow a developer to generate HTML dynamically. Django ships with its own Django Template Language (DTL), though alternative templating systems such as Jinja2 can be used. A template defines the structure and layout of an HTML file, with placeholders used to display data provided by the Django view.

16. What are static files, and why do we use them?

In Django, static files refer to JavaScript, CSS, images, and other media files that remain unchanged across the website. These files add styling, media content, and interactivity to a web application.

Static files are usually stored in a folder called static within an app or in a project-level static folder. Various configurations are required to serve static assets in production, but the local web server, accessed via runserver, serves them by default.

17. What does the settings.py file do?

The settings.py file stores the various configurations for a Django project and is automatically created when you start a new project using the startproject command. Essential configurations include database connections, apps, security policies, static file handling, middleware setup, and template configurations.

18. What database backends do you like to use with Django?

Django has official support for SQLite, PostgreSQL, MySQL, MariaDB, and Oracle. Because SQLite is file-based, it is used for local development by default. However, additional database backends can be used via third-party packages such as MongoDB.

19. How do you create backend APIs with Django?

Django does not have built-in support for APIs, but popular third-party packages, including Django REST Framework and django-ninja, allow developers to transform any existing Django project into an API quickly.

Intermediate Django Questions

20. What is the Django Templating Language?

The DTL is Django's built-in template system that allows for placeholder variables {{ variable }} and tags for logic inside the template, such as {% for %} and {% if %}. Some filters modify the display of variables like {{ name|lower }}, template inheritance via the {% extends %} tag, and more.

21. What are Q objects, and when would you use them?

Q objects are a way to make complex queries such as AND, OR, and NOT. They are combinable and reusable.

22. How does _set work with Django queries?

Django automatically creates the _set suffix when you define a ForeignKey relationship. It allows querying the "child" models related to a "parent" model in a one-to-many relationship.

23. Do you prefer function-based views (FBV) or class-based views (CBV)?

This is deliberately open-ended, and there isn't a correct answer. But the respondent should be able to explain how they differ and offer use cases for each. A terse response might be that function-based views display all the logic in one place and are, therefore, easier to reason about and use, whereas class-based views allow for inheritance and do not reuse code, especially when combined with built-in generic class-based views.

24. What are some third-party packages that you like to use?

There's no correct answer here, but being aware of Django Packages and resources like awesome-django is a plus. The responder should be able to mention a few packages they like to use and explain why.

Advanced Django Questions

25. What is a model manager? How and why would you use one?

By default, every Django model has at least one manager called objects used to generate QuerySets. It is a common technique to define custom model managers to handle common queries more efficiently.

26. What are Django signals?

Signals allow decoupled applications to be notified when actions occur elsewhere. The general pattern is to have a "listener" waiting for specific actions to happen and a "receiver," a function or method called when a signal is sent. Django has built-in signals such as pre_save, post_save, pre_delete, and post_delete. It is also possible to create custom signals. A typical pattern is to update a user profile model via signals whenever the primary User model is modified.

27. How does middleware work in Django?

Middleware is a framework of hooks that modify the request/response processing in a Django application. Middleware components perform various tasks such as session management, user authentication, cross-site request forgery protection, and more. The MIDDLEWARE setting in the settings.py file defines their order, but it is also possible to write custom middleware.

28. What are sessions?

Sessions are used in web applications to manage a user's information, activity, and preferences during a website visit. Each user is identified by a unique session ID sent to their browser as a cookie and returned to the server with each request. This allows the servers to retrieve stored session data. Common examples of sessions are user authentication and tracking items in a shopping cart before purchase. Django provides a number of configurations to enhance security around sessions.

29. Explain the Django request/response lifecycle in as much detail as possible.

This question could take up the entire interview! A first pass is that when a request comes in, Django creates an HttpRequest object with metadata about the request. Then, it hits the URL configuration, loads a view that passed in HttpRequest as a first argument, and the view returns an HttpResponse object. Bonus points for mentioning middleware, WSGI, and so on as needed.

30. When would you use the save() method versus form_valid()?

When creating or updating database records, the save() method is called and frequently overridden by adding custom logic before saving a model instance. form_valid() is used in class-based views where you need to handle valid form submissions. It is often used to process data or perform some action while saving the form.

31. What is logging, and why would you use it in a Django application?

Logging refers to recording events, errors, and informational messages that occur while an application is running. Django uses Python's built-in logging library, which can help with debugging, provide insights into application behavior, handle errors, and track down issues in production. Popular tools such as Sentry also go above and beyond the built-in support.

32. What is a mixin?

A mixin is a type of multiple inheritance that allows you to combine behaviors and attributes of more than one parent class. Django relies on mixins heavily because they are a good way to reuse code, but a potential downfall is that it can be difficult to analyze what exactly a class is doing and which methods to override.

33. When would you use a UUID in a URL?

You can use an id, slug, or UUID in your URLs. A Universally Unique Identifier (UUID) is a 128-bit number that can be used as a primary key and is especially helpful for security and privacy reasons when you don't want to reveal information like sequential IDs.

34. What are some caching strategies in Django?

Caching is a technique for storing output results so you don't have to query the database each time. Django has a built-in cache system for dynamic web pages, but it is also common to use Redis or Memcache for this.

35. What are select_related and prefetch_related?

These are two of the more common query optimization tools available via the Django ORM. select_related is used when selecting a single object via a one-to-one or one-to-many relationship. It performs a SQL join, so only one database query is needed. prefetch_related is when you need a set of things such as a many-to-many or reverse foreign key. The join happens in Python with a query for the original set of objects and one for each relationship, but it gathers all related objects in as few queries as possible.

Next Steps

While certainly not exhaustive, you will be in very good shape if you can answer these Django interview questions. Building out a small portfolio of Django projects is a great way to demonstrate your skills since an interviewer can ask questions about real-life projects rather than pose abstract questions.