Django
Django
Django MVT
To check more about Django's architecture, visit Django Project MVT Structure
Installing Django
Follow these steps to set up Django on your system:
1. Install Python 3:
Download and install the latest Python 3 version from the official website.
2. Install pip:
Pip comes with recent versions of Python. Open the command prompt and run:
pip --version
3. Set Up a Virtual Environment:
This isolates your project’s dependencies.
python -m virtualenv env_site
4. Activate the Environment:
Windows:
cd env_site\Scripts\activate
Mac/Linux:
source env_site/bin/activate
5. Install Django:
With your virtual environment active, run:
pip install django
Create a Django Project and App
1. Create a Django Project
Open the terminal and run:
django-admin startproject projectName
cd projectName
This creates a new folder named projectName containing your project settings
and then changes the current working directory to it..
2. Create a Django App
Inside the project directory (where manage.py is located), run:
python manage.py startapp projectApp
This creates a new app named projectApp.
Now you can see your directory structure as under :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projectApp'
]
We have finally created an app but to render it using urls we need to include the
app in our main project so that urls redirected to that app can be rendered.
4. Include App URLs in the Main Project
Edit projectName/urls.py to include your app’s URLs:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("projectApp.urls")), # Routes all other URLs to projectApp
]
Make sure you create a urls.py file inside projectApp to define your app’s
routes.
Using Django’s MVT Model
Once your project is set up:
Models: Define your data structure in projectApp/models.py.
Views: Create functions or class-based views in projectApp/views.py to
handle requests.
Templates: Create HTML templates in a templates folder (either in the
app or at the project level) and use Django’s templating language to
render dynamic content.
Programming
Role Web Framework
Language
General-purpose
Purpose Rapid web development
coding
Dependen
Independent Built using Python
cy
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
This is pure Python syntax, but written in Django's ORM structure.
Learning Path
To learn Django effectively, Python basics are a prerequisite:
1. Data types, functions, classes
2. File I/O, error handling
3. Virtual environments and pip (Python package manager)
Real-Life Analogy
Django is like a car (framework), but Python is the engine.
You can’t drive the car unless the engine (Python) works.
Installation of Django
Installing and setting up Django is a straightforward process. Below are the step-
by-step instructions to install Django and set up a new Django project on your
system.
Prerequisites: Before installing Django, make sure you have Python installed on
your system.
How to Install Django?
To Install Django in Linux and Mac is similar, here I am showing it in Windows for
Linux and Mac just open the terminal in place of the command prompt and go
through the following commands.
Step 1: Install Pip
Open the command prompt and enter the following command-
python -m pip install -U pip
Install Pip
Step 2: Set Virtual environment
Setting up the virtual environment will allow you to edit the dependency which
generally your system wouldn't allow. Follow these steps to set up a virtual
environment-
Step 3: Create virtual environment in Django
We should first go the directory where we want to create the virtual
environment then we type the following command to create virtual environment
in django.
python -m venv env_site
Install Django
Django Setup
Once Django is installed, we can start to create a new Django project.
Step 1: Start a new Django Project
Start a project by following command-
django-admin startproject geeks_site
Form Classes
Django Forms are used to gather input from users, validate that input, and
process it, often saving the data to the database. For example, when registering
a user, a form collects information like name, email, and password.
Django automatically maps form fields to corresponding HTML input elements. It
also handles:
Preparing data for rendering
Creating HTML forms
Processing submitted form data securely
While you can build forms using raw HTML, Django Forms simplify form creation
and validation, making your code cleaner and more secure.
Note that all types of work done by forms in Django can be done with advanced
HTML stuff, but Django makes it easier and efficient especially the validation
part. Once you get hold of forms in Django you will just forget about HTML forms.
Syntax:
Django form fields are defined much like Django model fields:
field_name = forms.FieldType(**options)
Befor creating forms, ensure that a django project and app is already set up,
refer to the following article to learn how to do it:
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Creating a Simple Django Form
Creating a form in Django is completely similar to creating a model, one needs to
specify what fields would exist in the form and of what type. For example, to
input, a registration form one might need First Name (CharField), Roll Number
(IntegerField), and so on.
Syntax:
from django import forms
class FormName(forms.Form):
# each field would be mapped as an input field in HTML
field_name = forms.Field(**options)
To create a form, create a forms.py file in you app folder:
from django import forms
class InputForm(forms.Form):
first_name = forms.CharField(max_length=200)
last_name = forms.CharField(max_length=200)
roll_number = forms.IntegerField(help_text="Enter 6 digit roll number")
password = forms.CharField(widget=forms.PasswordInput())
Render Django Forms
Django form fields have several built-in methods to ease the work of the
developer but sometimes one needs to implement things manually for
customizing User Interface(UI). A form comes with 3 in-built methods that can be
used to render Django form fields.
{{ form.as_table }} will render them as table cells wrapped in <tr> tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
To render this form into a view, move to views.py and create a home_view as
below.
from django.shortcuts import render
from .forms import InputForm
To check how to use the data rendered by Django Forms visit Render Django
Form Fields
Create Django Form from Models
Django ModelForm is a class that is used to directly convert a model into a
Django form. If you’re building a database-driven app, chances are you’ll have
forms that map closely to Django models. Now when we have our project ready,
create a model in geeks/models.py,
# import the standard Django Model
# from built-in library
from django.db import models
# create a ModelForm
class GeeksForm(forms.ModelForm):
# specify the name of model to use
class Meta:
model = GeeksModel
fields = "__all__"
Now visit http://127.0.0.1:8000/
Read Next: Python | Form validation using django
Django Forms Data Types and Fields List
The most important part of a form and the only required part is the list of fields it
defines. Fields are specified by class attributes. Here is a list of all Form Field
types used in Django
class
Select
TypedChoiceField TypedChoiceField(**kwargs)
NumberInput when
class FloatField(**kwargs) Field.localize is
FloatField False, else TextInput
NumberInput when
class IntegerField(**kwargs) Field.localize is
IntegerField False, else TextInput
class
GenericIPAddressField(**kwargs TextInput
GenericIPAddressField )
class
SelectMultiple
MultipleChoiceField MultipleChoiceField(**kwargs)
class
TypedMultipleChoiceFi TypedMultipleChoiceField(**kwa SelectMultiple
eld rgs)
class
NullBooleanSelect
NullBooleanField NullBooleanField(**kwargs)
Name Class HTML Input
Field
Options Description
help_text The help_text argument lets you specify descriptive text for this
Field. If you provide help_text, it will be displayed next to the
Field
Options Description
Validation
Django works on an MVT pattern. So there is a need to create data models (or
tables). For every table, a model class is created.
Suppose there is a form that takes Username, gender, and text as input from
the user, the task is to validate the data and save it.
In django this can be done, as follows:
Doing this compiles the models and if it didn't find any errors then, it creates a
file in the migration folder. Later run the command given below to finally reflect
the changes saved onto the migration file onto the database.
Now a form can be created. Suppose that the username length should not be
less than 5 and post length should be greater than 10. Then we define the
Class PostForm with the required validation rules as follows:
# Custom fields
fields =["username", "gender", "text"]
urlpatterns = [
path('', views.home, name ='index'),
]
Basically, this associates the ' ' url with a function home which is defined
in views.py file.
views.py file:
def home(request):
else:
{% load bootstrap3 %}
{% bootstrap_messages %}
<!DOCTYPE html>
<html lang="en">
<head >
<title>Basic Form</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
{% bootstrap_form form %}
<!-This is the form variable which we are passing from the function
of home in views.py file. That's the beauty of Django we
don't need to write much codes in this it'll automatically pass
all the form details in here
->
<div class="form-group">
<button type="submit" class="btn btn-default ">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Opening http://localhost:8000/ in the browser shows the following,
If a form with a username of length less than 5 is submitted, it gives an error at
the time of submission and similarly for the Post Text filled as well. The following
image shows how the form behaves on submitting invalid form data.