Logo F2FInterview

Django Interview Questions

Q   |   QA

Assume Bellow model for storing messages with timelines.

class Message(models.Model):
    from = models.ForeignKey(User,related_name = "%(class)s_from")
    to = models.ForeignKey(User, related_name = "%(class)s_to")
    msg = models.CharField(max_length=255)
    rating = models.IntegerField(blank='True',default=0)
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

Filter messages with specified Date and Time

today = date.today().strftime('%Y-%m-%d')

yesterday = date.today() - timedelta(days=1)
yesterday = yesterday.strftime('%Y-%m-%d')

this_month = date.today().strftime('%m')
last_month = date.today() - timedelta(days=32)
last_month = last_month.strftime('%m')
this_year = date.today().strftime('%Y')

last_year = date.today() - timedelta(days=367)
last_year = last_year.strftime('%Y')

today_msgs = Message.objects.filter(created_on__gte=today).count()
yesterday_msgs = Message.objects.filter(created_on__gte=yesterday).count()
this_month_msgs = Message.objects.filter(created_on__month=this_month,created_on__year=this_year).count()
last_month_msgs = Message.objects.filter(created_on__month=last_month,created_on__year=this_year).count()
this_year_msgs = Message.objects.filter(created_on__year=this_year).count()
last_year_msgs = Message.objects.filter(created_on__year=last_year).count()

There are 7 steps ahead to start Django project.

Step 1: Create project in terminal/shell

f2finterview:~$ django-admin.py startproject sampleproject

Step 2: Create application

f2finterview:~$ cd sampleproject/

f2finterview:~/sampleproject$ python manage.py startapp sampleapp

Step 3: Make template directory and index.html file

f2finterview:~/sampleproject$ mkdir templates

f2finterview:~/sampleproject$ cd templates/

f2finterview:~/sampleproject/templates$ touch index.html

Step 4: Configure initial configuration in settings.py

Add PROJECT_PATH and PROJECT_NAME

import os

PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
PROJECT_NAME = 'sampleproject'

Add Template directories path

TEMPLATE_DIRS = (
   os.path.join(PROJECT_PATH, 'templates'),
)

Add Your app to INSTALLED_APPS

INSTALLED_APPS = (
    'sampleapp',
)

Step 5: Urls configuration in urls.py

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns('',
    url(r'^$', 'sampleproject.sampleapp.views.index', name='index'),
)

Step 6: Add index method in views.py

from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext

def index(request):
    welcome_msg = 'Hello World'
    return render_to_response('index.html',locals(),context_instance=RequestContext(request))

Step 7: Add welcome_msg in index.html

<!DOCTYPE html>

<html>
<body>

<h1>My First Heading For Say...</h1>

<p>{{welcome_msg}}</p>

</body>
</html> 

Use bellow sample method to login with email or username.

from django.conf import settings
from django.contrib.auth import authenticate, login, REDIRECT_FIELD_NAME
from django.shortcuts import render_to_response
from django.contrib.sites.models import Site
from django.template import Context, RequestContext
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect

@csrf_protect
@never_cache
def signin(request,redirect_field_name=REDIRECT_FIELD_NAME,authentication_form=LoginForm):
    redirect_to = request.REQUEST.get(redirect_field_name, settings.LOGIN_REDIRECT_URL)
    form = authentication_form()
    current_site = Site.objects.get_current()
    if request.method == "POST":
        pDict =request.POST.copy()
        form = authentication_form(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            try:
                user = User.objects.get(email=username)
                username = user.username
            except User.DoesNotExist:
                username = username

            user = authenticate(username=username, password=password)

            # Log the user in.
    login(request, user)

    return HttpResponseRedirect(redirect_to)
  else:
    form = authentication_form()

  request.session.set_test_cookie()
  if Site._meta.installed:
    current_site = Site.objects.get_current()
  else:
    current_site = RequestSite(request)

  return render_to_response('login.html',locals(), context_instance=RequestContext(request))            

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:

  1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.
  2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.patterns().
  3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
  4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function (or a class based view). The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.
  5. If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. 

Model:

class Messages(models.Model):
    message_from = models.ForeignKey(User,related_name="%(class)s_from")
    message_to = models.ForeignKey(User,related_name="%(class)s_to")
    message=models.CharField(max_length=140,help_text="Your message")
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'messages'

Query:

messages = Messages.objects.filter(message_to = user).order_by('-created_on')[0]

Output:

message_from | message_to | message          | created_on

-------------|------------|------------------|--------------------

Stephen      | Anto       | Hi, How are you? | 2012-10-09 14:27:48

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: