Q21).What makes up Django architecture?
Ans21: Django runs on MVC architecture. Following are the components that make up django architecture:
- Models: Models elaborate back-end stuffs like database schema.(relationships)
- Views: Views control what is to be shown to end-user.
- Templates: Templates deal with formatting of view.
- Controller: Takes entire control of Models.A MVC framework can be compared to a Cable TV with remote. A Television set is View(that interacts with end user), cable provider is model(that works in back-end) and Controller is remote that controls which channel to select and display it through view.
Q22). What does session framework do in django framework ?
Ans22: Session framework in django will store data on server side and interact with end-users. Session is generally used with a middle-ware. It also helps in receiving and sending cookies for authentication of a user.
Q23).Can you create singleton object in python?If yes, how do you do it?
Ans23:
Yes, you can create singleton object. Here’s how you do it :
Default
1
2
3
4
5
|
class Singleton(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls,’_inst’):
cls._inst = super(Singleton,cls).__new__(cls,*args,**kwargs)
return cls._inst
|
Q24).Mention caching strategies that you know in Django!
Ans24: Few caching strategies that are available in Django are as follows:
- File sytem caching
- In-memory caching
- Using Memcached
- Database caching
Q25).What are inheritance type in Django?
Ans25: There are 3 inheritance types in Django
- Abstract base classes
- Multi-table Inheritance
- Proxy models
Q26).What do you think are limitation of Django Object relation mapping(ORM) ?
Ans26: If the data is complex and consists of multiple joins using the SQL will be clearer.
If Performance is a concern for your, ORM aren’t your choice. Genrally. Object-relation-mapping are considered good option to construct an optimized query, SQL has an upper hand when compared to ORM.
Q27):How to Start Django project with ‘Hello World!’? Just say hello world in django project.
Ans27: 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))
Step7: Add welcome_msg in index.html
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading For Say…</h1>
<p>{{welcome_msg}}</p>
</body>
</html>
Q28).How to login with email instead of username in Django?
Ans28: 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))
Q29).How Django processes a request?
Ans29: 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:
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.
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()
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
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.
If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view.
Q30).How to filter latest record by date in Django?
Ans30: 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