Logo F2FInterview

Django Interview Questions

Q   |   QA

Start by defining a custom signal. A custom signal here is a sub class of django.dispatch.Signal. This code can live in app/signals.py.

from django.dispatch import Signal
user_address_changed = Signal(providing_args=["user"])

Next, make sure you send this signal when your user's address is changed. Depending on how you have defined User and Address this can be done in different places. Let us assume that there is a view that lets users update their Address models. This code is presumably in app/views.py.

from app import signals

def update_address(request, *args, **kwargs):
    # all the changes go well.
    signals.user_address_changed.send(sender=None, user=request.user)
    # Render to template etc.

Now you need to set up a receiver for this signal.

from app.signals import user_address_changed

def handle_user_address_change(sender, **kwargs):
    """Trap the signal and do whatever is needed"""
    user = kwargs['user']
    # Write to log, update db, send mail etc.


from django.db.models import Count

This results in a query similar to

SELECT author, COUNT(author) AS author_count FROM books GROUP BY author

and the output would be of the form

[{'author': 'Stephen', 'author_count': 2},
{'author': 'Anto', 'author_count': 4}] 


Above mentioned middlewares are created by default while create Django project.

Common middleware
class CommonMiddleware

  • Forbids access to user agents in the DISALLOWED_USER_AGENTS setting, which should be a list of strings.
  • Performs URL rewriting based on the APPEND_SLASH and PREPEND_WWW settings.

If APPEND_SLASH is True and the initial URL doesn’t end with a slash, and it is not found in the URLconf, then a new URL is formed by appending a slash at the end. If this new URL is found in the URLconf, then Django redirects the request to this new URL. Otherwise, the initial URL is processed as usual.

For example, foo.com/bar will be redirected to foo.com/bar/ if you don’t have a valid URL pattern for foo.com/bar but do have a valid pattern for foo.com/bar/.

If PREPEND_WWW is True, URLs that lack a leading “www.” will be redirected to the same URL with a leading “www.”

Both of these options are meant to normalize URLs. The philosophy is that each URL should exist in one, and only one, place. Technically a URL foo.com/bar is distinct from foo.com/bar/ – a search-engine indexer would treat them as separate URLs – so it’s best practice to normalize URLs.

  • Sends broken link notification emails to MANAGERS if SEND_BROKEN_LINK_EMAILS is set to True.
  • Handles ETags based on the USE_ETAGS setting. If USE_ETAGS is set to True, Django will calculate an ETag for each request by MD5-hashing the page content, and it’ll take care of sending Not Modified responses, if appropriate.

Session middleware
class SessionMiddleware

  • Enables session support.

CSRF protection middleware
class CsrfViewMiddleware

  • Adds protection against Cross Site Request Forgeries by adding hidden form fields to POST forms and checking requests for the correct value.

Authentication middleware
class AuthenticationMiddleware

  • Adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object.

Message middleware
class MessageMiddleware

  • Enables cookie- and session-based message support.


Available other middlewares

Cache middleware
class UpdateCacheMiddleware
class FetchFromCacheMiddleware

  • Enable the site-wide cache. If these are enabled, each Django-powered page will be cached for as long as the CACHE_MIDDLEWARE_SECONDS setting defines.

View metadata middleware
class XViewMiddleware

  • Sends custom X-View HTTP headers to HEAD requests that come from IP addresses defined in the INTERNAL_IPS setting. This is used by Django’s automatic documentation system. Depends on AuthenticationMiddleware.

GZip middleware
class GZipMiddleware

Compresses content for browsers that understand GZip compression (all modern browsers).

It is suggested to place this first in the middleware list, so that the compression of the response content is the last thing that happens.

It will NOT compress content if any of the following are true:

  • The content body is less than 200 bytes long.
  • The response has already set the Content-Encoding header.
  • The request (the browser) hasn’t sent an Accept-Encoding header containing gzip.
  • The request is from Internet Explorer and the Content-Type header contains javascript or starts with anything other than text/. We do this to avoid a bug in early versions of IE that caused decompression not to be performed on certain content types.

You can apply GZip compression to individual views using the gzip_page() decorator.

Conditional GET middleware
class ConditionalGetMiddleware

  • Handles conditional GET operations. If the response has a ETag or Last-Modified header, and the request has If-None-Match or If-Modified-Since, the response is replaced by an HttpNotModified.

Also sets the Date and Content-Length response-headers.

Reverse proxy middleware
class SetRemoteAddrFromForwardedFor

Locale middleware
class LocaleMiddleware

  • Enables language selection based on data from the request. It customizes content for each user.

Bellow models are used for making complex query in Django.

class Subject(models.Model):
   name = models.CharField(max_length=300)

class School(models.Model):
   name = models.CharField(max_length=300)

class Students(models.Model):
   name = models.CharField(max_length=300)
   school = models.ForeignKey(School)
   join_date = models.DateField()

class Marks(models.Model):
   mark = models.IntegerField()
   student = models.ForeignKey(Students)
   subject = models.ForeignKey(Subject)

Here's how to do common aggregate queries and making complex queries , assuming the models above:

# Total number of students.
>>> Students.objects.count()

# Total number of students from school = Charvi School
>>> Students.objects.filter(school__name='Charvi School').count()

# Average marks across all subjects for a student.
>>> from django.db.models import Avg
>>> Marks.objects.filter(student__id=1).aggregate(Avg('mark'))
{'mark__avg': 90.5}

# Max marks across all subjects for a student.
>>> from django.db.models import Max
>>> Marks.objects.filter(student__id=1).aggregate(Max('mark'))
{'mark__max': Decimal('95')}

# Each school, each with a count of students as a "num_students" attribute.
>>> from django.db.models import Count
>>> school = School.objects.annotate(num_students=Count('Students'))
>>> school
[<School Charvi School>, <School St. Antony's>, ...]
>>> school[0].num_students

# The top 5 schools, in order by number of students.
>>> from django.db.models import Count
>>> pubs = School.objects.annotate(num_students=Count('students')).order_by('-num_students')[:5]
>>> pubs[0].num_students

Use a subset of Python's array-slicing syntax to limit your QuerySet to a certain number of results. This is the equivalent of SQL's LIMIT and OFFSET clauses.

For example, this returns the first 5 objects (LIMIT 5):

>>> Students.objects.all()[:5]

This returns the sixth through tenth objects (OFFSET 5 LIMIT 5):

>>> Students.objects.all()[5:10]

Negative indexing (i.e. Entry.objects.all()[-1]) is not supported.

Generally, slicing a QuerySet returns a new QuerySet -- it doesn't evaluate the query. An exception is if you use the "step" parameter of Python slice syntax. For example, this would actually execute the query in order to return a list of every second object of the first 10:

>>> Students.objects.all()[:10:2]

To retrieve a single object rather than a list (e.g. SELECT foo FROM bar LIMIT 1), use a simple index instead of a slice. For example, this returns the first Entry in the database, after ordering entries alphabetically by name:

>>> Students.objects.order_by('name')[0]

This is roughly equivalent to:

>>> Students.objects.order_by('name')[0:1].get()

Note, however, that the first of these will raise IndexError while the second will raise DoesNotExist if no objects match the given criteria.

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: