103. Explain Django Admin Interface?
Ans. The Django Admin interface is predefined interface made to fulfill the need of web developers as they won’t need to make another admin panel which is time-consuming and expensive.
Django Admin is application imported from django.contrib packages. It is operated by the organization itself and thus doesn’t need the extensive frontend.
Admin interface of Django has its own user authentication and most of the general features. It also offers lots of advanced features like authorization access, managing different models, CMS (Content Management System), etc.
104. Explain Django.
Ans. Django is web application framework which is a free and open source. Django is written in Python. It is a server-side web framework that provides rapid development of secure and maintainable websites.
105. What does Django mean?
Ans. Django Reinhardt, was a gypsy jazz guitarist from the 1930s to early 1950s who is known as one of the best guitarists of all time. The name was given Django after this person.
106. Which architectural pattern does Django follow?
Ans. Django follows Model-View-Template (MVT) architectural pattern.
The graph below shows the MVT based control flow.
Request is made by the user for a resource to the Django, Django works as a controller and check to the available resource in URL.
When the mapping of URL is found , a view is called that interact with model and template, it renders a template.
After that Django responds back to the user and sends a template as a response.
107. Explain Django architecture.
Ans. Django follows MVT (Model View Template) pattern. It is slightly different from MVC.
Model: It is the data access layer. It contains everything about the data, i.e., how to access it, how to validate it, its behaviors and the relationships between the data.
Let’s see an example. We are creating Employee model who has two fields first_name and last_name.
from django.db import models
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
View: It is the business logic layer. This layer contains the logic that accesses the model and defers to the appropriate template. It is like a bridge between the model and the template.
import datetime
# Create your views here.
from django.http import HttpResponse
def index(request):
now = datetime.datetime.now()
html = “<html><body><h3>Now time is %s.</h3></body></html>” % now
return HttpResponse(html) # rendering the template in HttpResponse
Template: It is a presentation layer. This layer contains presentation-related decisions, i.e., how something should be displayed on a Web page or other type of document.
For the configuration of the templates, we have to provide some entries in settings.py file.
TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [os.path.join(BASE_DIR,’templates’)],
‘APP_DIRS’: True,
‘OPTIONS’: {
‘context_processors’: [
‘django.template.context_processors.debug’,
‘django.template.context_processors.request’,
‘django.contrib.auth.context_processors.auth’,
‘django.contrib.messages.context_processors.messages’,
],
},
},
]
108. Explain the working of Django?
Ans. Django can be broken into following components:
Models.py : Models.py file will define your data model by extending your single line of code into full database tables and add a pre-built administration section to manage content.
Urls.py : Uses a regular expression to capture URL patterns for processing.
Views.py : This is main part of Django. The presentation logic is defined in this.
When a visitor visits Django page, first Django checks the URLs pattern you have created and use this information to retrieve the view. Then it is the responsibility of view to processes the request, querying your database if necessary, and passes the requested information to a template.
Then template renders the data in a layout you have created and displayed the page.
109. Name the foundation that manages the Django web framework?
Ans. Django is managed and maintained by an independent and non-profit organization named . Goal of foundation is to promote, support, and advance the Django Web framework.
110. Comment about Django’s stability?
Ans. Django is quite stable web development framework.There are many companies like Disqus, Instagram, Pinterest, and Mozilla that are using Django for many years.
111. Specify the features available in Django web framework?
Ans. Features available in Django web framework are:
Admin Interface (CRUD)
Templating
Form handling
Internationalization
A Session, user management, role-based permissions
Object-relational mapping (ORM)
Testing Framework
Fantastic Documentation
112. Explain the advantages of Django?
Ans. Advantages of Django:
Web development framework Django is a Python’s framework which is easy to learn.
It is clear and readable.
It is versatile.
It is fast to write.
No loopholes in design.
It is secure.
It is scalable.
It is versatile.
113. What are the disadvantages of Django?
Ans. Following is the list of disadvantages of Django:
Django’ modules are bulky.
It is completely based on Django ORM.
Components are deployed together.
You must know the full system to work with it.
114. What are the inheritance styles in Django?
Ans. There are three possible inheritance styles in Django:
1) Abstract base class: In this only parent’s class to hold information that you don’t want to type out for each child model then this style is used.
2) Multi-table Inheritance: This inheritance style is used if you are sub-classing an existing model and need each model to have its database table.
3) Proxy models: Proxy models is used, if you only want to modify the Python level behavior of the model, without changing the model’s fields.
115. Is Django a CMS i.e. content management system?
Ans. No, Django is not a CMS. But, it is a Web framework and a programming tool that makes you able to build websites.
116. Can you set up static files in Django? How?
Ans. Yes we can. We need to set three main things to set up static files in Django:
1) Set STATIC_ROOT in settings.py
2) run manage.py collect static
3) Static Files entry on the PythonAnywhere web tab
117. What is some typical usage of middlewares in Django?
Ans. Some usage of middlewares in Django is:
Session management,
Use authentication
Cross-site request forgery protection
Content Gzipping
118. What is the use of Django field class type?
Ans. Django field class type specifies:
The database column type.
Default HTML widget used to avail while rendering a form field.
The minimal validation requirements used in Django admin.
Automatic generated forms.
119. Explain the use of Django-admin.py and manage.py?
Ans. admin.py: This is Django’s command line utility for administrative tasks.
Manage.py: This file is created automatically in each Django project. It is a thin wrapper around the Django-admin.py. It has the following usage:
It puts your project’s package on sys.path.
DJANGO_SETTING_MODULE is the environment variable used to points to your project’s setting.py file.
120. What are the signals in Django?
Ans. Signals in Django are pieces of code which contain information about what is happening. A dispatcher is used to sending the signals and listen for those signals.
121. What are the two important parameters in signals?
Ans. Two important parameters in signals are:
Receiver: It specifies the callback function which connected to the signal.
Sender: It specifies a particular sender from where a signal is received.
122. How to handle URLs in Django?
In order to handle URL in Django, django.urls module is used by the Django framework.
Given below is the urls.py file of the project, lets see how it looks:
// urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path(‘admin/’, admin.site.urls),
]
We can see that, Django has already mentioned a URL here for the admin. Function path takes the first argument as a route of string or regex type.
Argument view is a view function which is used to return a response (template) to the user.
Module django.urls contains various functions, path(route,view,kwargs,name) is one of those which is used to map the URL and call the specified view.
123. What is Django Session?
Ans. In Django session is a mechanism to store information on the server side during the interaction with the web application. Session stores in the database and also allows file-based and cache based sessions, by default,
124 Explainthe role of Cookie in Django?
Ans. Cookie is nothing but a small piece of information which is stored in the client browser. Cookies are used to store user’s data in a file permanently (or for the specified time). There is an expiry date and time for each cookie and removes automatically when gets expire. There are built-in methods to set and fetch cookie provided by Django.
set_cookie() method is used to set a cookie and get() method is used to get the cookie.
request.COOKIES[‘key’] is an array which canbe used to get cookie values.
from django.shortcuts import render
from django.http import HttpResponse
def setcookie(request):
response = HttpResponse(“Cookie Set”)
response.set_cookie(‘java-tutorial’, ‘javatpoint.com’)
return response
def getcookie(request):
tutorial = request.COOKIES[‘java-tutorial’]
return HttpResponse(“java tutorials @: “+ tutorial);
125. What is the difference between Flask and Django?
Comparison Factor | Django | Flask |
Project Type | Supports large projects | Built for smaller projects |
Templates, Admin and ORM | Built-in | Requires installation |
Ease of Learning | Requires more learning and practice | Easy to learn |
Flexibility | Allows complete web development without the need for third-party tools | More flexible as the user can select any third-party tools according to their choice and requirements |
Visual Debugging | Does not support Visual Debug | Supports Visual Debug |
Type of framework | Batteries included | Simple, lightweight |
Bootstrapping-tool | Built-it | Not available |
126. How do you check for the version of Django installed on your system?
Ans:
To check for the version of Django installed on your system, you can open the command prompt and enter the following command:
- python -m django –version
You can also try to import Django and use the get_version() method as follows:
1 2 | import django
print (django.get_version())
|
127. What is the usage of middlewares in Django?
Ans: Middlewares are used go to modify the request i.e. HttpRequest object which is sent to the view, to modify the HttpResponse object returned from the view and to perform an operation before the view executes.
128. What are the roles of receiver and sender in signals?
- The receiver is the callback function which will be connected to a signal
- The sender specifies a particular sender to receive signals from
129. What does Django templates contain ?
Ans: Django templates contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.
130. How to create super user in django ?
To create a super user,,
- Create project using the django-admin startproject command.
- Move into the project location and run python manage.py makemigrations && python manage.py migrate && python manage.py createsuperuser
131. How to create simple application in django ?
To create a simple application use the command django-admin startproject followed by the application’s name.
132. What is ORM ? Advantages of ORM ?
ORM (Object-relational mapping) is a programming technique for converting data between incompatible type systems using object-oriented programming languages.
Advantages include:
- Concurrency support
- Cache management
133. How to create a model in django ?
Add the model object in the models.py file, updated settings for the newly created app by adding it to the INSTALLED_APPS section in settings.py, make migrations, and verify the database schema.
134. What is migration in django ?
Migrations are a way of propagating changes made in the model into the database schema (adding a field, deleting a model, etc.)
135. How to do migrations in django ?
To do migrations , create or update a model and in the app directory, run the command ./manage.py makemigrations <app name> && ./manage.py migrate <app name>
136. How to clear cache in django ?
To clear cache, run the clear() method from django.core.cache in a python script.
137. What is Rest API ?
A REST API is an application program interface that uses HTTP requests to GET, PUT, POST and DELETE data.
138. How to Create APIs in Django ?
Create a project directory, create python virtual environment, and activate it, install Django and djangorestframework using the pip install command. In the same project directory, create project using the command django-admin.py startproject api. Start the app. Add the rest_framework and the Djano app to INSTALLED_APPS to settings. Open the api/urls.py and add urls for the Django app. We can then create models and make migrations, create serializers, and finally wiring up the views.
139. What is DRF of Django Rest Frame work ?
Django Rest Framework (DRF) is a powerful module for building web APIs. It’s very easy to build model-backed APIs that have authentication policies and are browsable.
140. How to Fetch data from apis using Django ?
We use the Fetch API and SessionAuthentication by adding it to the settings.py file on the server and on the client, include the getCookie method. Finally, use the fetch method to call your endpoint.
141. How to update the data from apis ?
We update data by sending PUT requests. Add a new path in the data model urlpatterns from which the update will be sent to. We then add an update method to the serializer that will do the update.
142. What is Authentication ?
Authentication is the process or action of verifying the identity of a user or process.
143. Types of Authentication in REST API ?
Token based authentication and Session based authentication.
144. What is token based authentication system ?
A token based authentication system is a security system that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server
145. Can i use django apis in mobile application development ?
Yes
146. Explain Mixins in Django ?
A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used: to provide a lot of optional features for a class and to use one particular feature in a lot of different classes
147. Different types caching strategies in django ?
Different types of caching strategies include Filesystem caching, in-memory caching, using memcached and database caching.
148. How a request is process in Django ?
When the user makes a request of your application, a WSGI handler is instantiated, which:
- imports your settings.py file and Django’s exception classes.
- loads all the middleware classes it finds in the MIDDLEWARE_CLASSES or MIDDLEWARES(depending on Django version) tuple located in settings.py
- builds four lists of methods which handle processing of request, view, response, and exception.
- loops through the request methods, running them in order
- resolves the requested URL
- loops through each of the view processing methods
- calls the view function (usually rendering a template)
- processes any exception methods
- loops through each of the response methods, (from the inside out, reverse order from request middlewares)
- finally builds a return value and calls the callback function to the web server
149. When to use iterator in Django ORM ?
The iterator is used when processing results that take up a large amount of available memory (lots of small objects or fewer large objects).
150. What are signals in Django ?
Signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.
151. How to implement social login authentication in Django ?
Run the development server to make sure all is in order. The install python-social-auth using the pip install command. Update settings.py to include/register the library in the project Update the database by making migrations. Update the Project’s urlpatterns in urls.py to include the main auth URLs. Create a new app https://apps.twitter.com/app/new and make sure to use the callback url http://127.0.0.1:8000/complete/twitter. In the project directory, add a config.py file and grab the consumer key and consumer secret and add them to the config file. Finally add urls to the config file to specify the login and redirect urls. Do a sanity check and add friendly views.
152. Where to store static files in django ?
Static files are stored in the folder called static in the Django app.