Unit 1: Introduction to Django - Subjective Questions
INT253 — Web Development In Python Using Django • Practice Questions with Detailed Answers
20 questions
Define Django. Explain its main features and why it is used for web development.
Django is a free, open-source web framework written in Python. It helps developers build secure, maintainable, and database-driven web applications quickly.
Main features:
- Rapid development: Provides ready-to-use components for common web-development tasks.
- MVT architecture: Organizes applications into Model, View, and Template layers.
- Object-Relational Mapper (ORM): Allows developers to interact with databases using Python classes and methods.
- Automatic administration interface: Generates an admin panel for managing application data.
- URL routing: Maps requested URLs to appropriate view functions or classes.
- Template engine: Supports the creation of dynamic HTML pages.
- Security: Includes protection against CSRF, SQL injection, cross-site scripting, and clickjacking.
- Scalability: Can support applications ranging from small websites to large platforms.
Django is commonly used because it follows the Don't Repeat Yourself (DRY) principle, encourages reusable code, and includes most features required for server-side web development.
Explain the MVT architectural pattern used by Django.
Django follows the Model-View-Template (MVT) architectural pattern.
- Model: Defines the structure and behavior of application data. It communicates with the database through Django's ORM.
- View: Contains request-processing logic. A view receives an HTTP request, performs the required operations, and returns an HTTP response.
- Template: Defines the presentation layer, usually using HTML combined with Django Template Language expressions.
- URL dispatcher: Maps a URL pattern to the view responsible for processing that request.
Request flow:
- A browser sends an HTTP request.
- Django checks the URL configuration.
- The matching view is called.
- The view may retrieve or modify data through a model.
- The view passes context data to a template.
- The rendered response is returned to the browser.
MVT provides separation of concerns, making Django projects easier to test, maintain, and extend.
Describe the steps required to install Python and verify that it is installed correctly.
The general procedure for installing Python is:
- Download a supported Python version from the official Python website or install it through the operating system's package manager.
- Run the installer.
- On Windows, select Add Python to PATH before continuing.
- Complete the installation.
- Open a terminal or command prompt.
- Verify the installed version using
python --versionorpython3 --version. - Verify that the package installer is available using
pip --versionorpython -m pip --version.
A successful command displays the installed version, such as Python 3.x.x. Using python -m pip is often preferable because it explicitly uses the pip associated with the selected Python interpreter.
What is a Python virtual environment? Explain why and how it should be used in a Django project.
A virtual environment is an isolated Python environment containing its own interpreter links and installed packages. It prevents dependencies from one project from interfering with those of another project.
Benefits:
- Different projects can use different Django versions.
- Project dependencies remain isolated from system packages.
- Dependency management and deployment become more predictable.
- The global Python installation remains clean.
Creation and activation:
- Create it with
python -m venv venv. - On Windows, activate it with
venv\Scripts\activate. - On macOS or Linux, activate it with
source venv/bin/activate. - Install Django inside it with
python -m pip install django. - Leave it using
deactivate.
The environment should be activated whenever project commands are run. Its directory is normally excluded from version control.
Explain how to install Django and verify the installation.
Django should normally be installed inside an activated virtual environment.
Steps:
- Create a virtual environment with
python -m venv venv. - Activate the environment.
- Optionally upgrade
pipusingpython -m pip install --upgrade pip. - Install Django using
python -m pip install django. - Check the installed version using
python -m django --version. - Optionally inspect package details using
python -m pip show django.
If the installation is successful, the version command prints a Django version number. An error such as No module named django usually indicates that Django is not installed for the active Python interpreter or that the wrong virtual environment is active.
Describe how to set up a Django project in a code editor for efficient development.
A Django project can be prepared in an editor using the following process:
- Open the project's root directory in the editor.
- Create and activate a Python virtual environment.
- Select the virtual environment's Python interpreter in the editor.
- Install Django and other required dependencies.
- Install suitable Python support for linting, formatting, debugging, and code completion.
- Open the editor's integrated terminal and confirm the interpreter with
python --version. - Create or open the Django project from the directory containing
manage.py. - Configure environment variables for values such as secret keys and database credentials when required.
- Exclude generated or sensitive content, such as the virtual environment and local secrets, from version control.
Selecting the correct interpreter is important because the editor, debugger, terminal, and Django installation must refer to the same Python environment.
Distinguish between a Django project and a Django app, giving suitable examples.
A Django project is the complete web application and its site-wide configuration. A Django app is a focused, reusable module that implements a particular feature.
Project:
- Contains global settings, root URL configuration, and deployment configuration.
- Coordinates one or more apps.
- Usually has one
settings.pyand one rooturls.py. - Example: an entire online learning platform.
App:
- Handles a specific domain or feature.
- May contain models, views, URLs, templates, migrations, and tests.
- Can sometimes be reused in other projects.
- Examples:
courses,accounts,payments, orquizzes.
A project may contain many apps, while each app should ideally have a clear responsibility. Creating a separate app for every small function is unnecessary; app boundaries should represent meaningful features.
Describe the steps for creating and running your first Django project.
The following sequence creates and runs a basic Django project:
- Create a workspace directory and open it in a terminal.
- Create a virtual environment with
python -m venv venv. - Activate the virtual environment.
- Install Django using
python -m pip install django. - Run
django-admin startproject mysite. - Move into the generated directory using
cd mysite. - Apply initial migrations with
python manage.py migrate. - Start the development server with
python manage.py runserver. - Open
http://127.0.0.1:8000/in a browser.
The Django welcome page confirms that the project is running. The development server automatically reloads for many code changes, but it is intended only for development and should not be used as a production server.
Explain the purpose of the important files generated by django-admin startproject.
A newly generated Django project normally includes manage.py and an inner project package.
manage.py: Command-line utility for project-specific administrative tasks.__init__.py: Marks the inner directory as a Python package.settings.py: Stores project settings such as installed apps, middleware, databases, templates, static files, time zone, and security options.urls.py: Defines the root URL patterns and includes URL configurations from apps.asgi.py: Exposes the ASGI application object for asynchronous-compatible deployment.wsgi.py: Exposes the WSGI application object for traditional synchronous deployment.
The outer directory acts as the project workspace, while the inner directory is the Python package containing the site's main configuration.
Compare django-admin and manage.py. When should each command-line utility be used?
Both utilities execute Django administrative commands, but they differ in how project settings are supplied.
django-admin:
- Installed with Django and available as a general command-line tool.
- Commonly used to create a project with
django-admin startproject projectname. - May require the settings module to be provided through an option or environment variable for project-specific operations.
manage.py:
- Generated inside each Django project.
- Automatically points to that project's settings module.
- Commonly used for
runserver,migrate,makemigrations,test,shell, andcreatesuperuser.
Inside an existing project, python manage.py <command> is generally more convenient. Before a project exists, django-admin startproject is commonly used. python -m django can also invoke Django commands through the selected Python interpreter.
Explain the purpose and usage of the runserver command. Why is it unsuitable for production?
The runserver command starts Django's lightweight development web server.
Usage examples:
python manage.py runserverstarts it at127.0.0.1:8000.python manage.py runserver 8080changes the port to8080.python manage.py runserver 0.0.0.0:8000listens on all network interfaces.
It is useful for testing views, templates, URLs, and static assets during development. It also performs system checks and usually reloads when source files change.
It is unsuitable for production because it is not designed for production-level performance, hardening, reliability, or traffic management. A production deployment typically uses a suitable WSGI or ASGI server, secure settings, and often a reverse proxy.
Describe the functions of the makemigrations and migrate commands. Clearly distinguish between them.
Django migrations record and apply changes to the database schema.
python manage.py makemigrations: Detects changes in model definitions and creates migration files. It prepares a versioned description of schema operations.python manage.py migrate: Applies unapplied migration files to the configured database and records their status.
For example, after adding a field to a model, the developer normally runs makemigrations to generate the migration and then migrate to update the database.
Useful related commands include:
python manage.py showmigrationsto display migration status.python manage.py sqlmigrate app_name migration_nameto inspect the SQL associated with a migration.
Migration files should generally be committed to version control because they form part of the application's database history.
Explain any five commonly used manage.py commands and state their purposes.
Common manage.py commands include:
runserver: Starts Django's local development server.startapp app_name: Creates the initial directory structure for an app.makemigrations: Generates migration files after model changes.migrate: Applies database migrations.createsuperuser: Creates an account that can access the Django administration site.shell: Opens an interactive Python shell with Django configured.test: Discovers and runs automated tests.check: Examines the project for common configuration problems.
The available commands can be displayed using python manage.py help, while help for a particular command can be obtained using python manage.py help <command>.
Describe the procedure for creating a Django app and connecting it to an existing project.
To create and connect an app:
- Run
python manage.py startapp blogfrom the directory containingmanage.py. - Add the app configuration, such as
blog.apps.BlogConfig, toINSTALLED_APPSinsettings.py. - Define request handlers in
blog/views.py. - Create
blog/urls.pyand add app-specific URL patterns. - Include those URLs in the project's root
urls.py, for example withpath("blog/", include("blog.urls")). - Define database models in
blog/models.pyif the app stores data. - Run
python manage.py makemigrationsandpython manage.py migrateafter model changes. - Add templates, static resources, admin registrations, and tests as needed.
Creating an app only generates its structure. Registering it and integrating its URLs, models, and views make it part of the running project.
Explain the purpose of the standard files and directories generated by the startapp command.
The startapp command creates a basic app package containing:
__init__.py: Marks the app directory as a Python package.admin.py: Contains registrations and customizations for the Django admin site.apps.py: Defines the app's configuration class.models.py: Contains model classes representing application data.tests.py: Provides an initial location for automated tests.views.py: Contains function-based or class-based views that process requests.migrations/: Stores database migration files.migrations/__init__.py: Marks the migrations directory as a Python package.
Files such as urls.py, forms.py, template directories, and static directories are often added manually when the app requires them.
What is INSTALLED_APPS in Django? Explain why an app must usually be registered there.
INSTALLED_APPS is a setting in settings.py that lists the Django applications enabled for a project.
It commonly contains:
- Built-in Django apps for administration, authentication, sessions, messages, and static files.
- Third-party apps installed as dependencies.
- Locally developed project apps.
Registering an app allows Django's app registry to load its configuration and discover components such as models, migrations, management commands, and admin-related functionality. A local app can be registered by package name, such as blog, or by its configuration class, such as blog.apps.BlogConfig.
An unregistered app may still contain importable Python code, but Django will not treat it as an installed application, and model or migration behavior may fail or remain unavailable.
Explain how URL routing connects a browser request to a Django app and its view.
Django uses a URL dispatcher to map requested paths to views.
Routing process:
- The browser requests a path such as
/blog/. - Django reads the root
urlpatternsin the project'surls.py. - A
path()entry may useinclude()to delegate matching toblog/urls.py. - The app's URL configuration matches the remaining path.
- Django calls the corresponding view function or class.
- The view returns an
HttpResponsedirectly or renders a template.
A simple app route may use path("", views.index, name="index"). Separating root URLs from app URLs improves modularity. Named routes also allow templates and Python code to generate URLs without hard-coding path strings.
Describe the role of settings.py and explain important settings found in a newly created Django project.
settings.py is the central configuration module of a Django project.
Important settings include:
SECRET_KEY: Used for cryptographic signing and must be protected in production.DEBUG: Enables detailed error pages during development; it should be disabled in production.ALLOWED_HOSTS: Lists hostnames that the deployed site is permitted to serve.INSTALLED_APPS: Lists enabled Django, third-party, and local apps.MIDDLEWARE: Defines request and response processing components.ROOT_URLCONF: Identifies the root URL configuration module.TEMPLATES: Configures template engines and template discovery.DATABASES: Defines database connections; a new project commonly uses SQLite.LANGUAGE_CODEandTIME_ZONE: Control localization and time handling.STATIC_URL: Defines the base URL for static files.
Production secrets and environment-specific settings should normally be supplied securely rather than committed directly to source control.
Compare WSGI and ASGI in the context of a Django project. What are the purposes of wsgi.py and asgi.py?
WSGI and ASGI are interfaces between Python web applications and application servers.
WSGI:
- Primarily supports synchronous request-response applications.
- Is widely used for traditional Django deployments.
- Uses the application object exposed by
wsgi.py.
ASGI:
- Supports asynchronous capabilities in addition to synchronous code.
- Is suitable for long-lived connections and asynchronous workloads when the application and server support them.
- Uses the application object exposed by
asgi.py.
Both generated files set the project's settings module and expose an application callable that a compatible server can load. They are deployment entry points and generally contain little business logic.
Develop a complete command sequence for setting up a Django project with an app named students, and explain the purpose of each stage.
A typical setup sequence is:
python -m venv venvcreates an isolated environment.- Activate it using
venv\Scripts\activateon Windows orsource venv/bin/activateon macOS or Linux. python -m pip install djangoinstalls Django in that environment.django-admin startproject collegecreates the project.cd collegeenters the directory containingmanage.py.python manage.py startapp studentscreates the app structure.- Add
students.apps.StudentsConfigtoINSTALLED_APPS. - Create views and an app-level
urls.pyfor the required pages. - Include the app's URLs from the root URL configuration.
- Define any required models in
students/models.py. python manage.py makemigrationscreates migrations for model changes.python manage.py migrateapplies migrations to the database.python manage.py checkvalidates common project configuration.python manage.py runserverstarts the development server.
The site can then be tested at http://127.0.0.1:8000/. This sequence covers environment isolation, project creation, app creation, registration, routing, database preparation, validation, and local execution.
Define Django. Explain its main features and why it is used for web development.
Django is a free, open-source web framework written in Python. It helps developers build secure, maintainable, and database-driven web applications quickly.
Main features:
- Rapid development: Provides ready-to-use components for common web-development tasks.
- MVT architecture: Organizes applications into Model, View, and Template layers.
- Object-Relational Mapper (ORM): Allows developers to interact with databases using Python classes and methods.
- Automatic administration interface: Generates an admin panel for managing application data.
- URL routing: Maps requested URLs to appropriate view functions or classes.
- Template engine: Supports the creation of dynamic HTML pages.
- Security: Includes protection against CSRF, SQL injection, cross-site scripting, and clickjacking.
- Scalability: Can support applications ranging from small websites to large platforms.
Django is commonly used because it follows the Don't Repeat Yourself (DRY) principle, encourages reusable code, and includes most features required for server-side web development.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →