Pages

Saturday 8 April 2023

Web application using danjo & python

Introduction:

Django is a powerful web framework for Python that allows developers to quickly build web applications. It comes with a lot of built-in functionality, including an ORM, templating engine, and authentication system. In this article, we will explore how to use Django in Python using Visual Studio Code as the editor.

Setting Up a Virtual Environment:

Before we can start using Django in Python, we need to create a virtual environment to isolate our dependencies. A virtual environment is a self-contained environment that has its own Python interpreter and package dependencies. This makes it easy to manage dependencies for different projects and avoids conflicts between them.

Create a virtual environment

To create a virtual environment, we can use the venv module, which is included with Python 3. We can open the terminal in Visual Studio Code by selecting Terminal -> New Terminal from the menu bar. Then we can run the following command to create a virtual environment:

python3 -m venv myenv

This will create a new directory called myenv in our current directory, which contains the virtual environment.

Installing Django:

Once we have created a virtual environment, we can activate it by running the following command:

source myenv/bin/activate

This will activate the virtual environment and allow us to install packages specific to our project without affecting other projects on our system.


We can then install Django using pip:

pip install django

This will install the latest version of Django and all its dependencies.

Creating a Django Project:

Once we have installed Django, we can create a new Django project using the following command:

django-admin startproject myproject

This will create a new directory called myproject in our current directory, which contains the basic structure of a Django project. The startproject command creates a new Django project with the name myproject.

We can then navigate to the project directory by running the following command:

cd myproject

Creating a Django App:

In Django, a project consists of one or more apps, each of which represents a specific functionality of the project. We can create a new app using the following command:

python manage.py startapp myapp

This will create a new directory called myapp inside our project directory, which contains the basic structure of a Django app. The startapp command creates a new Django app with the name myapp.

We can then add our app to the project by editing the INSTALLED_APPS list in the settings.py file:

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'myapp', # Add our app here

]

This will add our app to the list of installed apps and make it available to the project.

Creating a View:


In Django, a view is a Python function that processes an HTTP request and returns an HTTP response. Views can be used to handle user input, perform database queries, and render templates. We can create a view in Django by defining a function that takes an HttpRequest object as an argument and returns an HttpResponse object.


Let's create a simple view that returns a "Hello, World!" message. In the views.py file of our app, we can define the following function:


from django.http import HttpResponse


def hello(request):

    return HttpResponse("Hello, World!")

This function takes an HttpRequest object as an argument and returns an HttpResponse object that contains the message "Hello, World!".


Creating a Template:

In Django, templates are used to generate HTML pages dynamically. Templates can contain placeholders for dynamic data, which are filled in at runtime. We can create a template in Django by defining an HTML file that contains template tags and filters.


Let's create a simple template that displays a list of items. In the templates directory of our app, we can create a new file called list.html with the following contents:

<!DOCTYPE html>

<html>

<head>

    <title>List</title>

</head>

<body>

    <h1>List of Items</h1>

    <ul>

        {% for item in items %}

            <li>{{ item }}</li>

        {% endfor %}

    </ul>

</body>

</html>

This template defines a list of items using a for loop and displays each item using a variable placeholder ({{ item }}).


Creating a URL:

In Django, URLs are used to map HTTP requests to views. URLs can contain named parameters and regular expressions, which allow us to handle dynamic URLs. We can create a URL in Django by defining a regular expression pattern that matches the desired URL and maps it to a view.


Let's create a URL that maps to our hello view and a URL that maps to a list view that displays our list.html template. In the urls.py file of our app, we can define the following URL patterns:

from django.urls import path

from . import views


urlpatterns = [

    path('hello/', views.hello, name='hello'),

    path('list/', views.list, name='list'),

]

This code defines two URL patterns, one that maps to the hello view using the URL path hello/ and one that maps to a list view using the URL path list/.

Creating a Model:


In Django, a model is a Python class that represents a database table. Models can be used to define the structure of our database tables, as well as the relationships between them. We can create a model in Django by defining a Python class that inherits from the django.db.models.Model class and defines the fields of our model as class attributes.


Let's create a simple model that represents a blog post. In the models.py file of our app, we can define the following model:

from django.db import models


class Post(models.Model):

    title = models.CharField(max_length=100)

    content = models.TextField()

    pub_date = models.DateTimeField(auto_now_add=True)

This code defines a Post model with three fields: a title field of type CharField, a content field of type TextField, and a pub_date field of type DateTimeField.

Creating a Form:

In Django, a form is a Python class that represents an HTML form. Forms can be used to collect user input and validate it before processing it. We can create a form in Django by defining a Python class that inherits from the django.forms.Form class and defines the fields of our form as class attributes.


Let's create a simple form that allows users to submit blog posts. In the forms.py file of our app, we can define the following form:

from django import forms

from .models import Post


class PostForm(forms.ModelForm):

    class Meta:

        model = Post

        fields = ['title', 'content']

This code defines a PostForm form that inherits from the ModelForm class and uses the Post model as its model. The fields attribute specifies which fields of the model should be included in the form.

Creating a Database:

Django comes with a built-in database ORM (Object-Relational Mapping) that allows us to work with databases using Python objects. By default, Django uses SQLite as its database backend, but it can also work with other database backends such as PostgreSQL and MySQL.


To create a database in Django, we need to define the database settings in the settings.py file of our project. We can define the database settings by adding the following code to the DATABASES dictionary in the settings.py file:

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': BASE_DIR / 'db.sqlite3',

    }

}

This code defines the default database backend as SQLite and specifies the name of the database file as db.sqlite3.


After defining the database settings, we need to create the database by running the following command in the terminal:

python manage.py migrate

This command will create the necessary tables in the database.


Performing Database Queries:

In Django, we can perform database queries using the database ORM. The ORM allows us to work with the database using Python objects and methods, without having to write SQL queries.


Let's perform some simple database queries to retrieve data from the Post model that we created in the previous article. In the views.py file of our app, we can define the following view functions:


from django.shortcuts import render

from .models import Post


def all_posts(request):

    posts = Post.objects.all()

    return render(request, 'all_posts.html', {'posts': posts})


def post_detail(request, post_id):

    post = Post.objects.get(id=post_id)

    return render(request, 'post_detail.html', {'post': post})

The all_posts view function retrieves all the posts from the Post model and renders them using the all_posts.html template. The post_detail view function retrieves a specific post from the Post model based on its ID and renders it using the post_detail.html template.


In the all_posts.html template, we can display the list of posts as follows:


{% for post in posts %}

    <h2>{{ post.title }}</h2>

    <p>{{ post.content }}</p>

{% endfor %}

In the post_detail.html template, we can display the details of a post as follows:

<h2>{{ post.title }}</h2>

<p>{{ post.content }}</p>

<p>{{ post.pub_date }}</p>

Working with Static Files:


Static files are files that are not generated dynamically by the server but are served as they are to the client. Examples of static files include CSS, JavaScript, and images.


In Django, we can serve static files by creating a static directory in our app and defining the static file settings in the settings.py file of our project. To create a static directory in our app, we can run the following command in the terminal:

mkdir myapp/static

Inside the static directory, we can create subdirectories for different types of static files. For example, we can create a css directory for CSS files, a js directory for JavaScript files, and an img directory for image files.

To define the static file settings in the settings.py file, we can add the following code:

STATIC_URL = '/static/'

STATICFILES_DIRS = [

    BASE_DIR / 'myapp/static',

]

This code defines the STATIC_URL as /static/ and specifies the location of the static directory in our app.


We can include the static files in our templates using the static template tag. For example, to include a CSS file in our template, we can use the following code:


{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

This code includes the style.css file located in the css directory of the static directory in our app.


Working with Media Files:

Media files are files that are uploaded by the users of our website, such as images and videos. In Django, we can handle media files by defining the media file settings in the settings.py file and creating a media directory in our app.

To define the media file settings in the settings.py file, we can add the following code:

MEDIA_URL = '/media/'

MEDIA_ROOT = BASE_DIR / 'myapp/media'

This code defines the MEDIA_URL as /media/ and specifies the location of the media directory in our app.


To handle media file uploads, we need to create a form that includes a FileField. For example, we can create a PostForm form that includes a image field for uploading images:

from django import forms

from .models import Post


class PostForm(forms.ModelForm):

    class Meta:

        model = Post

        fields = ('title', 'content', 'image')

To display the uploaded image in the template, we can use the url attribute of the image field. For example, we can display the image in the post_detail.html template as follows:


<h2>{{ post.title }}</h2>

<p>{{ post.content }}</p>

{% if post.image %}

    <img src="{{ post.image.url }}" alt="{{ post.title }}">

{% endif %}

Conclusion:

In this article, we have explored how to work with static and media files in Django using Visual Studio Code as the editor. We created a static directory for serving static files, defined the static file settings in the settings.py file, and included static files in our templates using the static template ta

1 comment:

  1. I really enjoyed reading your article, and it is good to know the latest updates. Do post more. Offshore Development Center in India. Keep on doing it. I am eagerly waiting for your updates. Thank you!


    ReplyDelete