Django interview questions

Django quiz questions

  • 1.

     Mention what command line can be used to load data into Django?

    Answer:

    To load data into Django you have to use the command line Django-admin.py loaddata. The command line will searches the data and loads the contents of the named fixtures into the database.

    View
  • 2.

    Explain the migration in Django and how you can do in SQL?

    Answer:

    Migration in Django is to make changes to your models like deleting a model, adding a field, etc. into your database schema.  There are several commands you use to interact with migrations.

    • Migrate
    • Makemigrations
    • Sqlmigrate

    To do the migration in SQL, you have to print the SQL statement for resetting sequences for a given app name.

    django-admin.py sqlsequencreset

    Use this command to generate SQL that will fix cases where a sequence is out sync with its automatically incremented field data.

    View
  • 3.

    Explain how you can use file based sessions?

    Answer:

    To use file based session you have to set the SESSION_ENGINE settings to “django.contrib.sessions.backends.file”

    View
  • 4.

    Explain the use of session framework in Django?

    Answer:

    In Django, the session framework enables you to store and retrieve arbitrary data on a per-site-visitor basis.  It stores data on the server side and abstracts the receiving and sending of cookies.  Session can be implemented through a piece of middleware.

    View
  • 5.

    Mention what does the Django templates consists of?

    Answer:

    The template is a simple text file.  It can create any text-based format like XML, CSV, HTML, etc.  A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.

    View
  • 6.

    Explain how you can setup static files in Django?

    Answer:

    There are three main things required to set up static files in Django

    • Set STATIC_ROOT in settings.py
    • run manage.py collectsatic
    • set up a Static Files entry on the PythonAnywhere web tab
    View
  • 7.

    Give an example how you can write a VIEW in Django?

    Answer:

    Views are Django functions that take a request and return a response.  To write a view in Django we take a simple example of “Guru99_home” which uses the template Guru99_home.html and uses the date-time module to tell us what the time is whenever the page is refreshed.  The file we required to edit is called view.py, and it will be inside mysite/myapp/

    Copy the below code into it and save the file

           from datatime import datetime

          from django.shortcuts import render

         def home (request):

                  return render(request, ‘Guru99_home.html’, {‘right_now’: datetime.utcnow()})

    Once you have determined the VIEW, you can uncomment this line in urls.py

    # url ( r ‘^$’ , ‘mysite.myapp.views.home’ , name ‘Guru99’),

    The last step will reload your web app so that the changes are noticed by the web server.

    View
  • 8.

    Explain how you can set up the Database in Django?

    Answer:

    You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.

    Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings

    • Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
    • Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.

    If you are not choosing SQLite as your database then setting like Password, Host, User, etc. must be added.

    View
  • 9.

    Explain how you can create a project in Django?

    Answer:

    To start a project in Django, you use command $ django-admin.py and then use the command

    Project

    _init_.py

    manage.py

    settings.py

    urls.py

    View
  • 10.

    Why Django should be used for web-development?

    Answer:

    • It allows you to divide code modules into logical groups to make it flexible to change
    • To ease the website administration, it provides auto-generated web admin
    • It provides pre-packaged API for common user tasks
    • It gives you template system to define HTML template for your web page to avoid code duplication
    • It enables you to define what URL be for a given function
    • It enables you to separate business logic from the HTML
    • Everything is in python
    View
  • 11.

    Mention what are the features available in Django?

    Answer:

    Features available in Django are

    • Admin Interface (CRUD)
    • Templating
    • Form handling
    • Internationalization
    • Session, user management, role-based permissions
    • Object-relational mapping (ORM)
    • Testing Framework
    • Fantastic Documentation
    View
  • 12.

    Explain what is Django?

    Answer:

    Django is a web framework in python to develop a web application in python.

    View
  • 13.

    What do you think are limitation of Django Object relation mapping(ORM) ?

    Answer:

    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.

    View
  • 14.

    List out the inheritance styles in Django?

    Answer:

    In Django, there is three possible inheritance styles

    • Abstract base classes: This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model
    • Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table
    • Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields
    View
  • 15.

    Mention caching strategies that you know in Django!

    Answer:

    Few caching strategies that are available in Django are as follows:

    • File sytem caching
    • In-memory caching
    • Using Memcached
    • Database caching
    View
  • 16.

    Can you create singleton object in python?If yes, how do you do it?

    Answer:

    Yes, you can create singleton object. Here’s how you do it :

    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

     

    View
  • 17.

    What does session framework do in django framework ?

    Answer:

    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.

    View
  • 18.

    What makes up Django architecture?

    Answer:

    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.
    View
  • 19.

    How do you make a Django app that is test driven and will display Fibonacci’s sequence?

    Answer:

    Keep in mind that it should take an index number and output the sequence. Additionally, there should be a page that shows the most recent generated sequences.

    Following is one of the solution for generating fibonacci series:

    def fib(n):
        "Complexity: O(log(n))"
        if n <= 0:
            return 0
        i = n - 1
        (a, b) = (1, 0)
        (c, d) = (0, 1)
        while i > 0:
            if i % 2:
                (a, b) = (d * b + c * a,  d * (b + a) + c * b)
            (c, d) = (c * c + d * d, d * (2 * c + d))
            i = i / 2
        return a + b

    Below is a model that would keep track of latest numbers:

    from django.db import models
     
    class Fibonacci(models.Model):
        parameter = models.IntegerField(primary_key=True)
        result = models.CharField(max_length=200)
        time = models.DateTimeField()

    For view, you can simply use the following code:

    from models import Fibonacci
     
    def index(request):
        result = None
        if request.method=="POST":
            try:
                n=int(request.POST.get('n'))
            except:
                return Http404
            try:
                result = Fibonacci.objects.get(pk=n)
                result.time = datetime.now()
            except DoesNotExist:
                result = str(fib(n))
                result = Fibonacci(n, result, datetime.now())
            result.save()
        return direct_to_template(request, 'base.html', {'result':result.result})

    You could use models to get last ‘n’ entities.

    View
  • 20.

    How do you use views in Django? 

    Answer:

    Views will take request to return response.  Let’s write a view in Django :  “example” using template example.html , using  the date-time module to tell us exact time of reloading the page.  Let’s edit a file called view.py, and it will be inside randomsite/randomapp/

    To do this save and copy following into a file:

    from datatime import datetime
     
          from django.shortcuts import render
     
         def home (request):
     
     
    return render(request, ‘Guru99_home.html’, {‘right_now’: datetime.utcnow()})

    You have to determine the  VIEW first, and then uncomment this line located in file urls.py

    # url ( r ‘^$’ , ‘randomsite.randomapp.views.home’ , name ‘example’),

    This will reload the site making changes obvious.

    View

© 2017 QuizBucket.org