DEV Community

Cover image for What is django?
Yash Patel
Yash Patel

Posted on • Edited on

What is django?

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.

So, Lets Dive In 🏊...!

Creating a Virtual Environment in Windows

windows

  1. Open the command prompt by pressing the Windows key + R and then typing cmd in the Run dialog box.
  2. 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 type cd Desktop.
  3. Once you're in the desired directory, enter the command python -m venv myenv to create a virtual environment named myenv. You can choose any name for your virtual environment.
  4. 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

mac/linux

  1. Open the terminal by pressing Command + Spacebar and then typing terminal in the Spotlight Search bar.
  2. 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 type cd Desktop.
  3. Once you're in the desired directory, enter the command python3 -m venv myenv to create a virtual environment named myenv. You can choose any name for your virtual environment.
  4. 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

  1. Open a command prompt or terminal window.
  2. 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.
  3. Once Python is installed, run the command pip install django to install Django.
  4. Wait for the installation to complete. This might take a few minutes depending on your internet connection speed.
  5. 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.

  1. Open your terminal or command prompt.
  2. Navigate to the directory where you have created virtual environment and make sure your virtual environment is activated.
  3. 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.

  4. 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.

  5. 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

  1. Open a terminal or command prompt.
  2. Navigate to the root directory of your Django project (the folder where manage.py is present).
  3. 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 called blog, you would run:

    python manage.py startapp blog
    
  4. Django will create a new directory with the name you provided for the app. The directory will contain several files and subdirectories.

  5. Open the settings.py file in your Django project folder and add the name of your app to the INSTALLED_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
    ]
    
  6. Save the settings.py file.

  7. You're now ready to start building your Django app!

  8. 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
Enter fullscreen mode Exit fullscreen mode

Let's break it down:

  1. project_name/ - This is the root directory of the Django project.
  2. app_name/ - This is a directory that contains a single Django app. You can have multiple apps within a single Django project.
  3. __init__.py - This is an empty file that tells Python that this directory should be considered a Python package.
  4. admin.py - This file is used to register models with the Django admin site.
  5. apps.py - This file is used to configure the Django app.
  6. models.py - This file contains the database models for the Django app.
  7. tests.py - This file contains the test cases for the Django app.
  8. views.py - This file contains the view functions for the Django app.
  9. settings.py - This file contains the settings for the Django - project, such as database configuration and installed apps.
  10. urls.py - This file contains the URL routing configuration for the Django project.
  11. wsgi.py - This file is used for deployment to WSGI-compatible servers.
  12. manage.py - This file is used to run management commands for the Django project.

Settings for static, media files

  1. 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.

  2. 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 and STATIC_ROOT are the directories where Django will look for your media and static files, respectively. MEDIA_URL and STATIC_URL are the URLs that will be used to access your media and static files.

  3. Update your project's URLs file
    In your project's urls.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 to True, then the static() and media() 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 and STATIC_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
Enter fullscreen mode Exit fullscreen mode

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 Django path function and any views that you want to associate with specific URLs.
from django.urls import path
from . import views
Enter fullscreen mode Exit fullscreen mode
  • 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'),
]
Enter fullscreen mode Exit fullscreen mode

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 the include function from Django's urls module, as well as the urls.py file of your app.
from django.urls import include, path
from myapp import urls as myapp_urls
Enter fullscreen mode Exit fullscreen mode

Here, we're assuming that our app is named myapp.

  • In the urlpatterns list of your project's urls.py file, add a path function for your app's URLs, using the include function to include your app's urls.py file.
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(myapp_urls)),
]
Enter fullscreen mode Exit fullscreen mode

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)