Django Docs Day 6 Updated
Django Docs Day 6 Updated
Django architecture
Django Installation
env_site\Script\deactivate to
deactivate
on linux / Mac
source env_site/bin/activate
or
source env_site/bin/deactivate
to deactivate
cd DoctorsProject
return HttpResponse("Hello
World !!!“)
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', hello_world),
]
================================================
==============
Types of Views
path('', index_page),
</body>
</html>
3. Go to views.py
4. Go to urls.py
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:
views.py
class AboutUs(View):
# 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.
def index(request):
return HttpResponse("Hello, world. This is
PatientApp.")
urlpatterns = [
path('', views.index),
]
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.
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')
def __str__(self):
return self.name + " - " +
self.gender
Username: admin
Password: **********
Password (again): *********
Superuser created successfully.
Visit http://127.0.0.1:8000/admin/
admin.site.register(Patient)
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:
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.
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
id =
models.AutoField(primary_key=Tru
e)
This is an auto-incrementing primary key.
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.
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)
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",
)
>>> 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’)
2. Create patient_list.html in
DoctorsProject/templates/PatientApp
folder
{% 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 %}
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)
path('all_patient/', views.all_patient),
Create patient_details.html in
DoctorsProject/templates/PatientApp
folder and add below html code
{{ patient }}
path('<int:patient_id>/', views.detail,
name='detail'),
selected_choice =
question.choice_set.get(pk=request.POST['choice'])
https://www.djangoproject.com/
Form Submission
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)
templates/PatientApp/add_patient.html
<br>
{% if message %}
<h3> {{message}} </h3>
{% endif %}
</form>
def add_patient(request):
return render(request, 'PatientApp/
add_patient.html')
path('add_patient/', views.add_patient),
path('add/', views.add),
1. In templates/PatientApp/patient_list.html update
<li> … </li> to provide delete patient option
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")
#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'),
Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [
...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
class PatientSerializer(serializers.ModelSerializer):
class Meta:
model = Patient
fields = ['name', 'age', 'gender',
'token_no']
#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)
@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)
Urls.py
#django-rest-framework
path('patient_api/patients/',
views.patient_list),
path('patient_api/patients/<int:pk>/',
views.patient_detail),
Delete Patient
DELETE - http://127.0.0.1:8000/patient/patient_api/patients/10/
DoctorsProject/PatientApp/static
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
<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) {
} );
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()
}
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>
<div id="#add_output">
result
</div>
</div>
</div>
</body>
//———————————————