0% found this document useful (0 votes)
57 views

Django Docs Day 6 Updated

Django is a Python-based web framework that allows for rapid development of efficient web applications. It provides pre-built components for common needs like user authentication, administration panels, and file uploads. Popular sites like Instagram, YouTube, and Spotify use Django. Django follows the MVT architecture pattern of having Models, Views, and Templates. Models represent the data structure, Views are the user interface, and Templates contain static and dynamic content. To install Django, create a virtual environment, install Django via pip, and then create and run a project with Django's utilities. Apps can then be created to organize specific functionality and connect to the project.

Uploaded by

kunal goyal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Django Docs Day 6 Updated

Django is a Python-based web framework that allows for rapid development of efficient web applications. It provides pre-built components for common needs like user authentication, administration panels, and file uploads. Popular sites like Instagram, YouTube, and Spotify use Django. Django follows the MVT architecture pattern of having Models, Views, and Templates. Models represent the data structure, Views are the user interface, and Templates contain static and dynamic content. To install Django, create a virtual environment, install Django via pip, and then create and run a project with Django's utilities. Apps can then be created to organize specific functionality and connect to the project.

Uploaded by

kunal goyal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Django

Django is a Python-based web framework that


allows you to quickly create efficient web
applications.

When you’re building a website, you always


need a similar set of components: a way to
handle user authentication (signing up,
signing in, signing out), a management panel
for your website, forms, a way to upload files,
etc. Django gives you ready-made
components to use and that too for rapid
development.

Companies using Django: Instagram, Disqus,


Pintrest, Mozilla Firefox, Spotify, Youtube

Django architecture

Django is based on MVT (Model-View-


Template) architecture. MVT is a software
design pattern for developing a web application.

MVT Structure has the following three parts –


Model: Model is going to act as the interface of
your data. It is responsible for maintaining data.
It is the logical data structure behind the entire
application and is represented by a database
(generally relational databases such as MySql,
Postgres).
View: The View is the user interface — what
you see in your browser when you render a
website. It is represented by HTML/CSS/
Javascript and Jinja files.
Template: A template consists of static parts of
the desired HTML output as well as some
special syntax describing how dynamic content
will be inserted.

Django Installation

1. python3 -m pip install -U pip

2. pip install virtualenv

3. Setup new virtual environment

Virtualenv is a tool that lets you create an


isolated Python environment for your project.
It creates an environment that has its own
installation directories, that doesn’t share
dependencies with
other virtualenv environments (and optionally
doesn’t access the globally installed
dependencies either). You can even configure
what version of Python you want to use for
each individual environment. It's very much
recommended to use virtualenv when dealing
with Python applications
.
a. Create a virtual environment by giving this
command in cmd -
virtualenv env_site

b. Activate virtual environment on Windows


env_site\Script\activate

env_site\Script\deactivate to
deactivate

on linux / Mac

source env_site/bin/activate
or
source env_site/bin/deactivate
to deactivate

4. pip install django for


Mac/Linux

py -m pip install django for


Windows

5. Create and Run Project


django-admin startproject
DoctorsProject

cd DoctorsProject

Python manage.py runserver

Now visit http://127.0.0.1:8000/ in


browser.

A Django Project when initialised contains


basic files by default such as manage.py,
view.py, etc. A simple project structure is
enough to create a single page application.
• _init_.py – It is python package.
• settings.py – As the name indicates it
contains all the website settings. In this file
we register any applications we create,
the location of our static files, database
configuration details, etc.
• urls.py – In this file we store all links of
the project and functions to call.
• wsgi.py – This file is used in deploying
the project in WSGI. It is used to help your
Django application communicate with the
web server.

6. Create HelloWorld MVT App

a. Create a new file views.py inside the


project folder where settings.py, urls.py and
other files are stored. save the following code
in it-

from django.http import


HttpResponse

def hello_world (request) :

return HttpResponse("Hello
World !!!“)

b. Open urls.py inside project folder


(DoctorsProject) and add your entry-

from DoctorsProject.views import


hello_world

urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', hello_world),
]

Now again run python manage.py


runserver on terminal/command prompt
Now visit http://127.0.0.1:8000/
hello in browser

================================================
==============

Working with MVT structure - Developing Views

Django Views are one of the vital participants of MVT Structure


of Django. A View is the user interface — what you see in your
browser when you render a website. It is represented by HTML/
CSS/Javascript and Jinja files. As per Django Documentation,
A view function is a Python function that takes a Web request
and returns a Web response. This response can be the HTML
contents of a Web page, or a redirect, or a 404 error, or an
XML document, or an image, anything that a web browser can
display.

Types of Views

Django views are divided into two major categories :-

• Function Based Views


• Class Based Views
To Add index view in the website with using Function Based
View
1. Add below code in views.py

def index_page (request) :

return HttpResponse("Welcome to my Website")

2. Open urls.py and import index_page as below

from DoctorsProject.views import index_page

and add index_page path in urlpatterns array as


below:

path('', index_page),

Now again run python manage.py runserver on


terminal/command prompt
Now visit http://127.0.0.1:8000/ in browser

Return static .html files as views

1. Create folder ‘templates’ in root folder of project where you


have manage.py file
2. Add ‘home.html’ in it with following contents
<html>
<body>

<form action = "" method = "get">


<label for="your_name">Your name: </label>
<input id="your_name" type="text"
name="your_name">
<input type="submit" value="OK">
</form>

</body>
</html>

3. Go to views.py

from django.shortcuts import render


# Create views from html.
def home_view(request):

# logic of view will be implemented here


return render(request, "home.html")

4. Go to urls.py

from DoctorsProject.views import home_view

add -> path('home/', home_view ), in url


patterns list

5. Open settings.py and change DIR value in


TEMPLATES
'DIRS': [os.path.join(BASE_DIR, 'templates')],

class-based views¶
Class-based views provide an alternative way to
implement views as Python objects instead of
functions. They do not replace function-based views,
but have certain differences and advantages when
compared to function-based views:

• Organization of code related to specific HTTP


methods (GET, POST, etc.) can be addressed by
separate methods instead of conditional
branching.
• Object oriented techniques such as mixins
(multiple inheritance) can be used to factor code
into reusable components.

Because Django’s URL resolver expects to send the


request and associated arguments to a callable
function, not a class, class-based views have
an as_view() class method which returns a
function that can be called when a request arrives for
a URL matching the associated pattern. The function
creates an instance of the class, calls setup() to
initialize its attributes, and then calls
its dispatch() method. dispatch looks at the
request to determine whether it is a GET, POST, etc,
and relays the request to a matching method if one
is defined, or raises HttpResponseNotAllowed if
not:

views.py

from django.http import HttpResponse


from django.views import View

class AboutUs(View):

def get(self, request):


# <view logic>
return HttpResponse('We provide all
solutions.')

# urls.py
from django.urls import path
from DoctorsProject.views import AboutUs

urlpatterns = [
path('about/', AboutUs.as_view()),
]
Projects vs. apps
An app is a Web application that does
something – e.g., a Weblog system, a
database of public records or a small poll
app. A project is a collection of configuration
and apps for a particular website. A project
can contain multiple apps. An app can be in
multiple projects.

6. Create an App in Project


Django is famous for its unique and fully
managed app structure. For every
functionality, an app can be created like a
completely independent module.

1. Go Inside your project folder where you


have manage.py. If you followed step 5 then
you are already there. Let’s create app with
the name PatientApp

run python manage.py startapp


PatientApp
if you are inside DoctorsProject folder
you will see :
DoctorsProject PatientApp
db.sqlite3 manage.py

if you open DoctorsProject folder in Visual Studio Code. It


should look like :

To consider the PatientApp in your project you need to specify


your PatientApp in INSTALLED_APPS list as follows in
settings.py:

Create Default View in PatientApp

Open PatientApp/views.py and add below code :

# Create your views here.


from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. This is
PatientApp.")

To render the app using urls we need to include


the app in our main project so that urls
redirected to that app can be rendered. Let us
explore it.
To create a URLconf in the PatientApp
directory, create a file called urls.py.

Add below code in PatientApp/urls.py


from django.urls import path

from . import views

urlpatterns = [
path('', views.index),
]

Move to DoctorsProject-> DoctorsProject ->


urls.py and add below code in the header

from django.urls import include

And include PatientApp urls in Project


urlpatterns list

path(“patient/“,
include(“PatientApp.urls")),
Models and Databases
By default, the configuration uses SQLite RDBMS.
SQLite is included in Python, so you won’t need to
install anything else to support your database.

If you wish to use another database, install the


appropriate database bindings and change the
following keys in the DATABASES 'default' item
to match your database connection settings in
DoctorsProject/settings.py
• ENGINE –
Either 'django.db.backends.sqlite3', 'd
jango.db.backends.postgresql', 'djang
o.db.backends.mysql',
or 'django.db.backends.oracle'.

Set TIME_ZONE = 'Asia/Kolkata' in


settings.py if you are in India

Run python manage.py migrate on terminal to


apply database setting changes

Create Model to represent Patient


Data

open PatientApp/models.py and add


below code to to create PatientModel

from django.db import models


from django.db.models import Model

# Create your models here.

class Patient(models.Model):
name =
models.CharField(max_length=100)
gender =
models.CharField(max_length=10)
age =
models.IntegerField(default=0)
token_no =
models.IntegerField(default=0)
pub_date =
models.DateTimeField('date published')

Now run python manage.py


makemigrations PatientApp

By running makemigrations, you’re telling Django


that you’ve made some changes to your models (in
this case, you’ve made new ones) and that you’d like
the changes to be stored as a migration.

Migrations are how Django stores changes to your


models (and thus your database schema) - they’re
files on disk

Now run python manage.py migrate

Now make changes in PatientApp/


models.py add below method to Patient
Model

def __str__(self):
return self.name + " - " +
self.gender

And again run

python manage.py makemigrations


PatientApp
python manage.py migrate

Introducing the Django


Admin - Django entirely automates creation of
admin interfaces for models.

Creating an admin user¶


First we’ll need to create a user who can login to the
admin site. Run the following command:

python manage.py createsuperuser

Enter your desired username and press enter.

Username: admin

You will then be prompted for your desired email


address:

Email address: [email protected]

The final step is to enter your password. You will be


asked to enter your password twice, the second time
as a confirmation of the first.

Password: **********
Password (again): *********
Superuser created successfully.

Now start App


python manage.py runserver

Visit http://127.0.0.1:8000/admin/

Make the PatientApp


Now

modifiable in the admin


Go to PationApp/admin.py and add below
code :

from .models import Patient

admin.site.register(Patient)

Again run python manage.py runserver


And Visit http://127.0.0.1:8000/admin/

More On Models

Field types¶
Each field in your model should be an instance of
the appropriate Field class. Django uses the
field class types to determine a few things:

• The column type, which tells the database


what kind of data to store
(e.g. INTEGER, VARCHAR, TEXT).
• The default HTML widget to use when
rendering a form field
(e.g. <input type="text">, <select>).
• The minimal validation requirements, used in
Django’s admin and in automatically-
generated forms.
Django ships with dozens of built-in field types;
you can find the complete list in the model field
reference. You can easily write your own fields if
Django’s built-in ones don’t do the trick;
see Writing custom model fields.

Field options¶
Each field takes a certain set of field-specific
arguments (documented in the model field
reference). For example, CharField (and its
subclasses) require a max_length argument
which specifies the size of the VARCHAR database
field used to store the data.

There’s also a set of common arguments available


to all field types. All are optional. They’re fully
explained in the reference, but here’s a quick
summary of the most often-used ones:

null
If True, Django will store empty values as NULL in
the database. Default is False.

blank
If True, the field is allowed to be blank. Default
is False.

medal = models.CharField(blank=True
max_length=10)
Primary Key

Automatic primary key fields¶

By default, Django gives each model the following


field:

id =
models.AutoField(primary_key=Tru
e)
This is an auto-incrementing primary key.

If you’d like to specify a custom primary key,


specify primary_key=True on one of your
fields.
name =
models.CharField(max_length=100,
primary_key=True)

Note that this is different than null. null is


purely database-related, whereas blank is
validation-related. If a field has blank=True,
form validation will allow entry of an empty value.
If a field has blank=False, the field will be
required.

choices
A sequence of 2-tuples to use as choices for this
field. If this is given, the default form widget will
be a select box instead of the standard text field
and will limit choices to the choices given.

A choices list looks like this:

from django.db import models

class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name =
models.CharField(max_length=60)
shirt_size =
models.CharField(max_length=1,
choices=SHIRT_SIZES)

Foreign Key setup


from django.db import models

class Musician(models.Model):
first_name =
models.CharField(max_length=50)
last_name =
models.CharField(max_length=50)
instrument =
models.CharField(max_length=100)

class Album(models.Model):
artist =
models.ForeignKey(Musician,
on_delete=models.CASCADE)
name =
models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()

ForeignKey
(OneToMany), ManyToManyField and OneToO
neField require the first argument to be a model
class, so use the verbose_name keyword
argument:

poll = models.ForeignKey(
Poll,
on_delete=models.CASCADE,
verbose_name="the related poll",
)
sites = models.ManyToManyField(Site,
verbose_name="list of sites")
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
verbose_name="related place",
)

Python Shell and Writing ORM queries

On terminal quit running server and


open python shell using

python manage.py shell

Now import Patient model and fetch all


Patient object using code:
>>> from PatientApp.models import Patient
>>> Patient.objects.all()

<QuerySet [<Patient: Token :1, Name: - Ankur, Age


- 23 Gender - male>, <Patient: Token :4, Name: -
mehul, Age - 12 Gender - male>]>

>>> result = Patient.objects.all()


>>> for p in result:
... print(p)
...
Token :1, Name: - Ankur, Age - 23 Gender - male
Token :4, Name: - mehul, Age - 12 Gender - male

To Add new Patient Object in PatientApp


DB

>>> from django.utils import timezone


>>> pnew = Patient(token_no=3, name="Neha",
age=21, gender="female", pub_date=timezone.now())
>>>
>>> pnew.save()
>>>
>>> Patient.objects.all()
<QuerySet [<Patient: Token :1, Name: - Ankur, Age
- 23 Gender - male>, <Patient: Token :4, Name: -
mehul, Age - 12 Gender - male>, <Patient: Token
:3, Name: - Neha, Age - 21 Gender - female>]>

Filter Object using field value

>>> Patient.objects.filter(token_no=1)
<QuerySet [<Patient: Token :1, Name: - Ankur, Age
- 23 Gender - male>]>
>>>

>>> Patient.objects.filter(gender="male")
<QuerySet [<Patient: Token :1, Name: - Ankur, Age
- 23 Gender - male>, <Patient: Token :4, Name: -
mehul, Age - 12 Gender - male>]>

>>> Patient.objects.order_by(‘-gender’)

Fetch and display all Patients


using a url
1. Create ‘PatientApp’ sub folder in
‘templates’ folder to store PatientApp
html templates

2. Create patient_list.html in
DoctorsProject/templates/PatientApp
folder

and add below html code

{% if latest_patient_list %}
<ul>
{% for patient in latest_patient_list %}
<li><a href="/patient/{{ patient.id }}/">
{{ patient.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No patient are available.</p>
{% endif %}

Here assume that latest_patient_list is list


of patient objects
3. Open DoctorsProject/PatientApp/views.py and add
below code

def all_patient(request):

latest_patient_list = Patient.objects.order_by('-
pub_date')
context = { 'latest_patient_list':
latest_patient_list, }
return render(request, 'PatientApp/
patient_list.html', context)

This function fetches all patients and renders using


patient_list.html template

4. Now go to DoctorsProject/PatientApp/urls.py and


add url for all_patient view function

path('all_patient/', views.all_patient),

5. Create template to display individual patient .

Create patient_details.html in
DoctorsProject/templates/PatientApp
folder and add below html code

{{ patient }}

6. Open DoctorsProject/PatientApp/views.py and add


below code

from django.shortcuts import get_object_or_404


# ...
def detail(request, patient_id):
patient = get_object_or_404(Patient,
pk=patient_id)
context = {'patient': patient}
return render(request, 'PatientApp/
patient_details.html', context)

This function get patient by patient_id and renders


using patient_detail.html template

7. Now go to DoctorsProject/PatientApp/urls.py and


add url for detail view function

path('<int:patient_id>/', views.detail,
name='detail'),

selected_choice =
question.choice_set.get(pk=request.POST['choice'])

https://www.djangoproject.com/

Form Submission

Update PatientApp/views.py index function to include link


for patient_list and add_patient form

def index(request):
content = "Hello, world. This is
PatientApp<br><br>"
content = content + "<a href='all_patient/' > All
Patient</a> <br><br>"
content = content + "<a href='add_patient/' > ADD
Patient</a> <br>"

return HttpResponse(content)

1. Add New Patient Entry form in

templates/PatientApp/add_patient.html

<form action="../add/" method="POST">


{% csrf_token %}
Name : <input type="text" name="name"
value="" /><br>
Gender : Male <input type="radio" name="gender"
value="male" />
Female <input type="radio" name="gender"
value="male" /><br>
Age : <input type="text" name="age"
value="1" /><br>
Token : <input type="text" name="token"
value="0" /><br>

<input type="submit" name="submit"


value="Submit" /><br>

<br>
{% if message %}
<h3> {{message}} </h3>
{% endif %}
</form>

<br><br><a href='../' > Back</a> <br>

2. Add view functions to receive submitted data and


save to database

Add below code in PatientApp/views.py

def add_patient(request):
return render(request, 'PatientApp/
add_patient.html')

from django.utils import timezone


def add(request):
name = request.POST['name']
age = request.POST['age']
gender = request.POST['gender']
token = request.POST['token']

patient = Patient(name=name, age=age,


gender=gender,token_no=token,
pub_date=timezone.now())
message = ""
try:
patient.save()
message = "Patient data submitted."
except:
message = ("Can't save patient details. try
again")
context = {'message':message}

return render(request, 'PatientApp/


add_patient.html', context)

3. Update PatientApp/urls.py to link above view


functions

path('add_patient/', views.add_patient),
path('add/', views.add),

Delete Patient Record

1. In templates/PatientApp/patient_list.html update
<li> … </li> to provide delete patient option

<li><a href="/patient/{{ patient.id }}/">


{{ patient.name }}- {{ patient.name }}
</a>
| <a href="/patient/{{ patient.id }}/
delete_patient/">DELETE</a>
</li>

2. Create view function to handle delete request .


Add below code in PatientApp/views.py
def delete_patient(request, patient_id):

patient = get_object_or_404(Patient,
pk=patient_id)

message = ""
try:
patient.delete()
message = "Patient data deleted."
except:
message = ("Can't delete patient details. try
again")

message = message + "<br><br><a href='../../


all_patient/'>Back</a>"

#context = {'message':message}

return HttpResponse(message)
3. Add path for delete url in PatientApp/
urls.py

path('<int:patient_id>/delete_patient/',
views.delete_patient, name='delete_patient'),

Django REST framework is a powerful and


flexible toolkit for building Web APIs.
Installation
Install using pip, including any optional
packages you want...
pip install djangorestframework
pip install markdown # Markdown
support for the browsable API.
pip install django-filter #
Filtering support

Add 'rest_framework' to your INSTALLED_APPS setting.

INSTALLED_APPS = [
...
'rest_framework',
]

In Settings.py add below element

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}

Create RESTFull JSON API for patient model


In DoctorsProject/PatientApp create serializers.py
and put below code.

from .models import Patient


from rest_framework import serializers

class PatientSerializer(serializers.ModelSerializer):
class Meta:
model = Patient
fields = ['name', 'age', 'gender',
'token_no']

Serializers allow complex data such as


querysets and model instances to be converted
to native Python datatypes that can then be
easily rendered into JSON, XML or other content
types. Serializers also provide deserialization,
allowing parsed data to be converted back into
complex types, after first validating the
incoming data.

Add below code in Views.py

#django-rest-framework
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from .models import Patient
from .serializers import PatientSerializer

@csrf_exempt
def patient_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
patients = Patient.objects.all()
serializer = PatientSerializer(patients,
many=True)
return JsonResponse(serializer.data,
safe=False)

elif request.method == 'POST':


data = JSONParser().parse(request)
serializer = PatientSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data,
status=201)
return JsonResponse(serializer.errors,
status=400)

@csrf_exempt
def patient_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
patient = Patient.objects.get(pk=pk)
except Patient.DoesNotExist:
return HttpResponse(status=404)

if request.method == 'GET':
serializer = PatientSerializer(patient)
return JsonResponse(serializer.data)

elif request.method == 'PUT':


data = JSONParser().parse(request)
serializer = PatientSerializer(patient,
data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors,
status=400)

elif request.method == 'DELETE':


patient.delete()
return HttpResponse(status=204)

Urls.py
#django-rest-framework
path('patient_api/patients/',
views.patient_list),
path('patient_api/patients/<int:pk>/',
views.patient_detail),

Now Run App and u


Get all patient
GET - http://127.0.0.1:8000/patient/patient_api/patients/
Get one patient
GET - http://127.0.0.1:8000/patient/patient_api/patients/10/

Create new patient


POST - http://127.0.0.1:8000/patient/patient_api/patients
body
{
"name": "Raj Malhotra",
"age": 21,
"gender": "male",
"token_no": 88
}

Update Existing Patient


PUT - http://127.0.0.1:8000/patient/patient_api/patients/10
body
{
"name": "Raj Sharma”,
"age": 22,
"gender": "male",
"token_no": 88
}

Delete Patient

DELETE - http://127.0.0.1:8000/patient/patient_api/patients/10/

Integrate JQuery in Django

First, make a folder named static inside your app folder:

DoctorsProject/PatientApp/static

Then download jQuery file e.g. jquery-1.8.0.js. and


Save it in the static folder.

Inside your settings.py file make sure


that django.contrib.staticfiles is
under INSTALLED_APPS (it is there by default).

Now create your html code file that uses jquery and put in
template/PatientApp. Let us assume that file name is
jquery_patient_crud.html

And include jquery as below.


<script type="text/javascript"
src="{{ STATIC_URL }} /static/jquery-1.8.0.js">
</script>

Create url for this jquery_patient_crud.html in


PatientApp/urls.py

//HTML JQUERY CODE to ACCESS GET, POST,


PUT, DELETE URL
Sample jquery_customer_crud.html

<html>
<head>
<title> Demo 1 </title>
<script src="{{static}}/static/
jquery-3.5.0.min.js" ></script>

<script>

function getAllCustomer()
{

$("#all").html("downloading...");
var myurl = "http://
127.0.0.1:8000/customer/customer_api/customers/";

$.get(myurl, function(data,
status) {

var customers = data;


var result = "<table>";
result = result + "<tr> <td>
Acc no </td> <td> Name </td> " +
"<td> Balance </
td> <td> Acc Type </td></tr>";

for (let index = 0; index <


customers.length; index++) {
var obj =
customers[index];
result = result +
"<tr><td>" + obj.account_no + "</td>" +
" <td>"
+ obj.name + "</td>" +
" <td>"
+ obj.balance + "</td>" +
" <td>"
+ obj.account_type + "</td>" +
" <td>"
+ "<input type='button'
onclick='deleteCustomer("+obj.id+")' value='Delete' /
>" + "</td>" + "</tr>" ;
}
result = result + "</
table" ;
$("#all").html(result);

} );

function deleteCustomer(custId)
{
alert("Delete:"+custId);
$.ajax({
type: "DELETE",
url: "http://127.0.0.1:8000/
customer/customer_api/customers/"+custId+"/",
data: {}
}).done(function( msg ) {
alert( " Deleted: " );
getAllCustomer();
});

$(document).ready( function () {

$("#button1").click(getAllCustomer);

$("#submit_data").click( function(){
var myURL = "http://
127.0.0.1:8000/customer/customer_api/customers/";

var obj = {
"name" : $("#name").val(),
"gender" : $
('input[name=gender]:checked').val(),
"balance" : $
("#balance").val(),
"account_type" : $
('input[name=account_type]:checked').val(),
"account_no" : $
("#account_no").val()
}

// $.get(myURL, callback, xhr,


datatype);
$.post(myURL,
JSON.stringify(obj),
function(data, status)
{

alert("Success-"+status);
getAllCustomer();
},
'json' );

});
});

</script>
<meta name="viewport" content="width=device-
width, initial-scale=1">
<style>
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}

</style>
</head>
<body>

<div style="padding-left:16px">
<h2>Welcome to Customer Portal</h2>
<p>Here you can find list of all customer and
add new customer.</p>
</div>

<div>
<div class="topnav">
<input type="button" value="Show All"
id="button1"/>
</div>

<div id="all" style="height: 90%; width:


40%;float: left; background-color: azure;">

</div>

<div id="add" style="padding: 20px; height:


90%; width: 50%;float: right; background-color:
azure;">
<br> Customer Name : <input type="text"
name="name" value="" id="name"/>
<br> Gender : Male <input type="radio"
checked name="gender" value="male" id="genderMale"/>
Female <input type="radio"
name="gender" value="female" id="genderFemale" />

<br> Account Type : Savings <input


type="radio" checked name="account_type"
value="savings" id="atSavings" />
Current <input
type="radio" name="account_type" value="current"
id="atCurrent" />

<br> Balance : <input type="text"


name="balance" value="0" id="balance" />
<br> Account No. : <input type="text"
name="account_no" value="0" id="account_no"/>

<br> <input id="submit_data"


type="button" value="Submit" />

<div id="#add_output">
result
</div>
</div>
</div>

</body>
//———————————————

Setup a demo python-jango


website at
https://www.pythonanywhere.com/

You might also like