Django is a high-level Python web framework that enables the rapid development of secure and maintainable websites and web applications. It follows the Model-View-Controller (MVC) architectural pattern, but with some variations, such as using the Model-View-Template (MVT) pattern instead.
Django provides a robust set of tools and libraries for handling common web development tasks, such as handling forms, authentication, routing, database migrations, and more. It also emphasizes the concept of "batteries included", which means that it includes many useful features out of the box, so developers don't have to spend time building everything from scratch.
Django is a popular choice for web development due to its simplicity, scalability, and versatility. It is used by many companies and organizations, including Instagram, Spotify, Mozilla, and The Washington Post, among others.
Creating a Virtual Environment in Windows
- Open the command prompt by pressing the
Windows key + R
and then typingcmd
in the Run dialog box. - Navigate to the directory where you want to create your virtual environment using the
cd
command. For example, to navigate to the desktop, you can typecd Desktop
. - Once you're in the desired directory, enter the command
python -m venv myenv
to create a virtual environment namedmyenv
. You can choose any name for your virtual environment. - Activate the virtual environment by entering the command
source myenv\Scripts\activate
. You should see the name of your virtual environment appear in parentheses in the command prompt.
Creating a Virtual Environment in Mac/Linux
- Open the terminal by pressing
Command + Spacebar
and then typingterminal
in the Spotlight Search bar. - Navigate to the directory where you want to create your virtual environment using the
cd
command. For example, to navigate to the desktop, you can typecd Desktop
. - Once you're in the desired directory, enter the command
python3 -m venv myenv
to create a virtual environment namedmyenv
. You can choose any name for your virtual environment. - Activate the virtual environment by entering the command
source myenv/bin/activate
. You should see the name of your virtual environment appear in parentheses in the terminal.
That's it! You have successfully created a virtual environment in both Windows and Mac/Linux. Now you can install any packages or dependencies required for your project within the virtual environment without affecting the system-wide Python installation.
Installing Django
- Open a command prompt or terminal window.
- Check if Python is already installed on your system by running the command
python --version
. If Python is not installed, download and install Python from the official website. - Once Python is installed, run the command pip install django to install Django.
- Wait for the installation to complete. This might take a few minutes depending on your internet connection speed.
- Once the installation is complete, verify the installation by running the command
django-admin --version
. This should output the version number of Django installed on your system.
Congratulations! You have successfully installed Django on your local machine. You can now start building your web applications using the Django web framework.
How to Create a New Django Project.
- Open your terminal or command prompt.
- Navigate to the directory where you have created virtual environment and make sure your virtual environment is activated.
-
Run the following command to create a new Django project:
django-admin startproject project_name
Replace
project_name
with the name you want to give your project. -
Once the project is created, navigate to the project directory using the following command:
cd project_name
Again, replace
project_name
with the name of your project. -
To test that your project has been created successfully, run the following command:
python manage.py runserver
This will start the development server. You should be able to see the Django welcome page by navigating to
http://localhost:8000/
in your web browser.
That's it! You've successfully created a new Django project.
How to create Django App
- Open a terminal or command prompt.
- Navigate to the root directory of your Django project (the folder where
manage.py
is present). -
Run the following command:
python manage.py startapp <app_name>
Replace
<app_name>
with the name of your app. For example, if you want to create an app calledblog
, you would run:
python manage.py startapp blog
Django will create a new directory with the name you provided for the app. The directory will contain several files and subdirectories.
-
Open the
settings.py
file in your Django project folder and add the name of your app to theINSTALLED_APPS
list. For example:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', # Add your app name here ]
Save the
settings.py
file.You're now ready to start building your Django app!
Now run
python manage.py migrate
command to apply any pending database migrations to the database schema.
Now let's understand Django App file structure
project_name/
├── app_name/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── project_name/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
Let's break it down:
-
project_name/
- This is the root directory of the Django project. -
app_name/
- This is a directory that contains a single Django app. You can have multiple apps within a single Django project. -
__init__.py
- This is an empty file that tells Python that this directory should be considered a Python package. -
admin.py
- This file is used to register models with the Django admin site. -
apps.py
- This file is used to configure the Django app. -
models.py
- This file contains the database models for the Django app. -
tests.py
- This file contains the test cases for the Django app. -
views.py
- This file contains the view functions for the Django app. -
settings.py
- This file contains the settings for the Django - project, such as database configuration and installed apps. -
urls.py
- This file contains the URL routing configuration for the Django project. -
wsgi.py
- This file is used for deployment to WSGI-compatible servers. -
manage.py
- This file is used to run management commands for the Django project.
Settings for static, media files
Set up media and static file directories
First, create two directories named "media" and "static" in your project directory to store your media and static files, respectively. To do this, simply create two folders in the root directory of your project.-
Update the project settings file
In your project settings file, add the following lines of code to specify the directories where your static and media files will be stored:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/'
Here,
MEDIA_ROOT
andSTATIC_ROOT
are the directories where Django will look for your media and static files, respectively.MEDIA_URL
andSTATIC_URL
are the URLs that will be used to access your media and static files. -
Update your project's URLs file
In your project'surls.py
file, add the following code to serve the static and media files:
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here,
DEBUG
is a Boolean value in your settings file that determines whether your application is running in debug mode or not. If it is set toTrue
, then thestatic()
andmedia()
functions will serve your media and static files, respectively.Now, you can access your media and static files using the URLs you specified in the
MEDIA_URL
andSTATIC_URL
settings.
After following above steps your django file structure should look something like this.
project_name/
├── app_name/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ ├── views.py
│ └── static/
├── project_name/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── static/
└── manage.py
App and Project urls connection
- In your app's directory, create a file named
urls.py
. This file will contain all of the URLs for your app. - In the
urls.py
file of your app, import the Djangopath
function and any views that you want to associate with specific URLs.
from django.urls import path
from . import views
- Define your app's URLs using the
path
function. This function takes two arguments: the URL pattern and the view function that should handle the request.
urlpatterns = [
path('home/', views.home, name='home'),
path('contact/', views.contact, name='contact'),
]
In this example, we've defined two URLs for our app: /home/ and /contact/. The first argument of the path function specifies the URL pattern, and the second argument is the view function that should handle the request. We've also given each URL a name using the name argument. This is useful when generating URLs in templates or views.
- In your project's main
urls.py
file, import theinclude
function from Django'surls
module, as well as theurls.py
file of your app.
from django.urls import include, path
from myapp import urls as myapp_urls
Here, we're assuming that our app is named myapp
.
- In the
urlpatterns
list of your project'surls.py
file, add apath
function for your app's URLs, using theinclude
function to include your app'surls.py
file.
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(myapp_urls)),
]
In this example, we've added a path
function for our app's URLs using the include
function. The empty string ''
specifies that our app's URLs should be included at the root URL of our project.
Overall, this directory structure provides a clear separation of concerns between the project-level and app-level components of a Django application. Understanding this structure is key to building scalable and maintainable Django projects.
Top comments (0)