PYFlask is the simplified way to get a web services front end to our Python Application.
Django is for real world complexity PYTHON web applications including build SOA front ends.

Python Django: Student Lab Workbook

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
Built by experienced developers, it takes care of much of the low level details of web application development, so you can focus delivering the Use Cases of the Business Domain of your Application.
You do this by calling the provided API method calls of the Framework.

Why Use Django?

Rapid Development: Django's philosophy is to do more with less code, making the development process faster.
All components are Included: Comes with a wide array of built-in features for common web development tasks.
Secure: Designed to help developers avoid common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically.
Scalable: Can handle high traffic, making it suitable for both small and large-scale projects.
Versatile: Used for all types of websites, from content management systems to social networks to scientific computing platforms.
[For your project: You will present some business domain to deliver with a DJANGO SOA web application.

How Does Django Work?

Django follows the Model-View-Template (MVT) architecture.
For the MODEL, for your project you will be using PYMONGO.
Model: The model is not the database. The model is the set of APIs that provide the data access layer, to enable access the database.
For your project, you will be setting up and connecting to an Mongo Database in the Cloud (MONGO DB Atlas).
View: The website point of interaction with the user, handling requests and returning responses.
Template: The presentation layer, responsible for formatting and displaying data to the user.

Setting Up Django


Python 3.6 or higher installed.
Basic knowledge of Python.


Create a Virtual Environment (optional but recommended):
This keeps dependencies required by different projects separate.
python -m venv django_env source django_env/bin/activate
# On Windows use `django_env\Scripts\activate`
Install Django:
pip install django

Starting a Django Project

Create a New Project:
django-admin startproject myproject
cd myproject
This creates a new directory myproject with the basic structure of a Django project. Do a CD into your new myproject directory.
Start the Development Server:
python runserver
Access the server at You now see a success page.
1. **Introduction to `django-admin` and `startproject` command**: - `django-admin`: The `django-admin` command-line utility is used to manage various aspects of a Django project, including creating a new project, creating applications within the project, running development servers, and performing database-related tasks.
`django-admin` is a Python script that serves as a command-line utility to manage various aspects of a Django project, such as creating new projects, creating applications within the project, running development servers, and performing database-related tasks.
When Django is installed, the `django-admin` script becomes available for use in the command line, regardless of the shell or terminal being used.
- `startproject`: The `startproject` command is used to create a new Django project, which includes the necessary directory structure and files to get started with a Django application.
2. **Location of the `django-admin` command**: - The `django-admin` command is a built-in command-line utility provided by the Django framework. - This command is made available through the installation of Django, and it is accessible from the command line after installing Django as a Python package.
`django-admin` is located within the Python environment after installing the Django framework.
When Django is installed as a Python package, the `django-admin` command-line utility is made available in the system.
Once Django is installed, you can access `django-admin` from the command line, enabling you to manage and create Django projects effortlessly.

3. **Understanding the availability of the `startproject` command**: - Upon installation of Django, the `startproject` command becomes available through the `django-admin` utility. - This command is specifically designed to initiate the creation of a new Django project, providing a convenient way to set up the initial project structure and configuration files.
4. **Execution of the command**: - When you run `django-admin startproject <project_name>`, the `django-admin` utility internally triggers the `startproject` command, which then generates the necessary files and directories for a new Django project.
5. **Contribution to project creation**: - The availability of the `startproject` command through `django-admin` simplifies the process of creating new Django projects, allowing developers to kick-start their projects efficiently.
6. Further Information: - For detailed documentation and further insights into the `django-admin` and `startproject` command, refer to the official Django documentation [Django Official Documentation](
By utilizing the `django-admin` utility and the `startproject` command, developers can initialize new Django projects seamlessly, thanks to the convenience and automation offered by the Django framework.
Seeing the Django template page when you visit `http://localhost:8000/` indicates that your Django development server is running correctly, and your basic Django setup is working as expected.
to setup the Admin Panel and database: python migrate

This is a good foundation to start building your web application.

1. **Explore the Admin Site**: - Django comes with a built-in admin interface. You can access it by going to `http://localhost:8000/admin`. - Before accessing it, you'll need to create a superuser account.

python createsuperuser

Run `python createsuperuser` and follow the prompts. - Once the superuser is created, navigate to the admin site and log in to explore Django's admin functionalities.
2. Develop Your Application: - Start adding more functionalities to your `myapp`.
You can create models in `myapp/`, which Django will use to create database tables.
- After creating models, remember to run `python makemigrations myapp` and `python migrate` to apply the changes to the database.

###Here are the detailed instructions for the Python Django lab:
Docusing on creating a superuser
Dxploring the admin site
Developing your application with models and migrations:
1. **Create a Superuser**: - Open a terminal or command prompt and navigate to the root directory of your Django project (where the `` file is located). - Run the command: `python createsuperuser` - Follow the prompts to create a superuser account: - Enter a username for the superuser (e.g., admin). - Provide an email address for the superuser (optional). - Enter a strong password for the superuser and confirm it. - After successfully creating the superuser, you will see a message indicating that the superuser was created successfully.
Explore the Admin Site:
- Start the Django development server by running the command: `python runserver` - Open a web browser and navigate to the admin site URL: `http://localhost:8000/admin/` - On the admin login page, enter the superuser credentials you created earlier (username and password). - Once logged in, you will be redirected to the Django administration dashboard. - Explore the various sections and functionalities provided by the admin site, such as managing users, groups, and any other models registered in the admin.

2. **Develop Your Application**:
Create Models
- Open the `` file located in your application's directory (`myapp/`). - Define your models by creating Python classes that inherit from `django.db.models.Model`. - Add fields to your models to represent the data attributes you want to store in the database. - For example, let's create a simple `Book` model: ```python from django.db import models
class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) publication_date = models.DateField()
def __str__(self): return self.title ```
// *** think about
// 1. What is your Business Domain for your Project:
In the `` file in your Django application, you need to define your models by creating Python classes that inherit from `django.db.models.Model` and add fields to represent the data attributes you want to store in the database.
Here's a general structure to guide you:
1. **Import Django Models**: - Begin by importing the necessary modules from Django's `models`:
```python from django.db import models ```
2. **Define Models**: - Create Python classes for each of your models, and ensure that they inherit from `models.Model`:
```python class YourModelName(models.Model): # Define your model fields by adding class attributes field1 = models.CharField(max_length=100) field2 = models.IntegerField() # Add other fields as needed ```
Replace `YourModelName` with the name you want to assign to your model, and define the fields within the class as per your Business Domain Analysis and what Use Cases you want to deliver in your Application.
Here's a breakdown of the fields you can use: - `CharField`: A field for character strings. - `IntegerField`: A field for storing integers. - `DateField`: A field for storing dates. - `ForeignKey`: A field used to create a many-to-one relationship.
3. **Field Options**: - You can specify various options for each field, such as `max_length` for `CharField`, `blank`, `null`, and more.
Refer to the Django documentation for detailed information on field options.

4. **Meta Class** (Optional): - You can define a `Meta` class to specify further options for the model:
```python class YourModelName(models.Model): # Define your fields here # ...
class Meta: verbose_name = "Your Model Name" verbose_name_plural = "Your Model Names" ```
Ensure that you replace `Your Model Name` with the appropriate names for your model.
After defining your models and fields in the `` file, you can run Django's migration commands to create the corresponding database tables based on your models. All thanks to the Django ORM Object relationship Mapper.

**Create and Apply Migrations**: - After defining your models, you need to create migration files to reflect the changes in the database schema. - Open a terminal or command prompt and navigate to the root directory of your Django project. - Run the command: `python makemigrations myapp` - This command generates migration files based on the changes detected in your models. - Apply the migrations to the database by running the command: `python migrate` - This command executes the migration files and creates the corresponding database tables.
**Verify the Changes**: - Start the Django development server by running the command: `python runserver` - Open a web browser and navigate to the admin site URL: `http://localhost:8000/admin/` - Log in using your superuser credentials. - Verify that your newly created models are visible in the admin interface. - You can now interact with your models through the admin site, adding, editing, and deleting instances as needed.
Remember to continue developing your application by adding more models, views, and templates as per your project requirements. Regularly run the `makemigrations` and `migrate` commands whenever you make changes to your models to keep the database schema in sync with your application's structure.
These instructions should help you create a superuser, explore the admin site, and develop your application with models and migrations in the Python Django lab.
3. Experiment with Views and Templates: - Enhance your views in `myapp/` to return more complex HTML responses. You can also use Django's template system for this. - Create a `templates` directory within your app to store HTML files, and render these templates in your views.

4. **Static Files**: - Learn how to manage static files (CSS, JavaScript, images). Create a `static` directory in your app for these files.
5. **Read Django Documentation**: - Django's official documentation ( is incredibly comprehensive and useful for learners of all levels. It's a great resource for both reference and learning.
6. **Build and Experiment**: - The best way to learn Django is by building projects. Start with simple ones and gradually increase complexity.
7. **Community and Resources**: - Join Django forums and communities. Sites like Stack Overflow, Reddit’s Django community, and DjangoProject’s forum can be invaluable.
Remember, the Django development server is intended for development purposes only. When you're ready to deploy your app for production, you'll need to set it up with a more robust web server and possibly a different database, among other things.
Happy coding, and enjoy your journey with Django!

Creating an App

Django projects consist of 'apps', modular components that can be reused across different projects.
Create an App:
python startapp myapp
Replace myapp with the name of your app.
Write Views:
In myapp/, write a simple view as an example:
pythonCopy code
from django.http import HttpResponse def home(request): return HttpResponse("Hello, world. You're at the myapp home.")
Map URLs:
In myapp/ (create this file if it doesn't exist):
pythonCopy code
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]
Update Project URLs:
In myproject/, include the myapp URLs:
pythonCopy code
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/',, path('myapp/', include('myapp.urls')), ]
View in Browser:
Run python runserver again and visit to see the message from the view.

Why Create a Django Project?

Creating a Django project is the first step in building a web application. It structures your code and provides a foundation upon which you can build and scale your web application according to your needs.


This workbook has introduced you to Django, a powerful framework for web development with Python.
By following the steps outlined, you now have a basic understanding of setting up a Django project and the rationale behind using Django for web development. Keep experimenting and learning to become more proficient in Django!

To locate the Django installable that needs to be added to the system's PATH environment variable, you can follow these steps based on the provided information:

1. **Identify the Python Scripts Directory**: - The Django installable, specifically the `django-admin` command, is typically located in the Python Scripts directory. - The Python Scripts directory is where Python installs scripts and executables when you use pip to install packages like Django.
2. **Locate the Python Scripts Directory**: - Depending on your operating system and Python installation method, the Python Scripts directory can be found in different locations: - For Windows: The Python Scripts directory is often located at `C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXX\Scripts`, where `PythonXX` corresponds to your Python version. - For macOS/Linux: The Python Scripts directory is usually located in the bin folder of your Python installation path.
3. **Add Django to the PATH**: - Once you have identified the Python Scripts directory, you need to add it to your system's PATH environment variable. - This allows your command prompt or terminal to locate and execute Django commands like `django-admin` from any directory.
4. **Update the PATH Environment Variable**: - To add Django to the PATH: - **Windows**: 1. Search for "Environment Variables" in the Start menu and select "Edit the system environment variables." 2. In the System Properties window, click on "Environment Variables." 3. In the Environment Variables window, under "System variables," find the PATH variable and select it. Click "Edit." 4. Add a new entry with the path to your Python Scripts directory (e.g., `C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXX\Scripts`). 5. Click "OK" to save the changes. - **macOS/Linux**: 1. Open your shell configuration file (e.g., `.bashrc`, `.zshrc`) using a text editor. 2. Add a line like `export PATH="$PATH:/path/to/python/scripts"` at the end of the file, replacing `/path/to/python/scripts` with the actual path to your Python Scripts directory. 3. Save and close the file. 4. Run `source ~/.bashrc` or `source ~/.zshrc` (or restart your terminal) to apply the changes.
By following these steps and adding the Django installable location (Python Scripts directory) to your system's PATH environment variable, you should be able to run Django commands like `django-admin` from any location in your command prompt or terminal without encountering errors related to command recognition.
Citations: [1]

The error message `'django-admin' is not recognized as an internal or external command, operable program or batch file` means that Django is not installed in your Python environment, or the Python Scripts directory is not included in your system's PATH environment variable.

This means that the command prompt or terminal cannot find the `django-admin` executable to run it.

Here are steps to resolve this issue, based on the context of Python and Django usage as outlined in the provided course material:

### 1. Ensure Django is Installed
First, make sure Django is installed in your Python environment. You can install Django using pip, which is the package installer for Python. Open your command prompt or terminal and run the following command:
```bash pip install django ```
If you're using a virtual environment (which is a best practice for Python development to manage dependencies), ensure that the virtual environment is activated before running the above command. If Django is already installed, pip will indicate that Django is already satisfied. If not, pip will proceed to install Django.
### 2. Verify Django Installation
After installation, you can verify that Django has been installed correctly by checking the version of Django. Run the following command:
```bash django-admin --version ```
This command should return the version of Django that is installed, indicating that `django-admin` is now recognized.
### 3. Add Python Scripts to PATH (If Necessary)
If you've confirmed that Django is installed but are still encountering the error, the issue may be that your system's PATH environment variable does not include the directory where Python scripts are installed. Follow these steps to add Python Scripts to your PATH:
- **Windows**: 1. Search for "Environment Variables" in the Start menu and select "Edit the system environment variables." 2. In the System Properties window, click on "Environment Variables." 3. In the Environment Variables window, under "System variables," find the PATH variable and select it. Click "Edit." 4. If the path to your Python Scripts directory is not there, click "New" and add the path. The Python Scripts directory is typically located at `C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXX\Scripts`, where `PythonXX` corresponds to your Python version. 5. Click "OK" to close all dialogs and apply the changes.
- **macOS/Linux**: - Typically, the PATH is set correctly if Python is installed via Homebrew (macOS) or the package manager on Linux. However, if you need to add it manually, you can add a line to your `.bashrc`, `.zshrc`, or equivalent shell configuration file like so: ```bash export PATH="$PATH:/path/to/python/scripts" ``` - Replace `/path/to/python/scripts` with the actual path to your Python Scripts directory.
After adding Python Scripts to your PATH, open a new command prompt or terminal window and try running `django-admin` again.
### Conclusion
Following these steps should resolve the issue with `django-admin` not being recognized. This allows you to proceed with Django development, including starting new projects and applications as part of your coursework in Python II, which includes developing web applications using the Django framework[1].
Citations: [1]
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.