Share and Learn To Write Code!

Programming articles, which help you to build your application. If something you are stuck to code and complete the program, just find here your question-related articles.

Share with   

How to write HTML view using python django

How to write rest api html views using python django framework.
Django   Python   HTML   API   Website  

Django HTML Response


We are going to see how we can write api to send Json data using JsonResponse Method in django rest framework.


Django


Django is a high-level Python web framework.

It energizes fast advancement and spotless.

Django's essential objective is to facilitate the production of complex, database-driven websites.

Django is kept up by the Django Software Foundation.


Django HttpResponse


In the following example we are create dajngo project for sending api which is having JSON object response.


Prerequisite

Install Python

Install Django click for how to install Django and python.


Setup


Create Python Virtual Environment

mkvirtualenv json_response_demo

Install Django

pip install django

Create Django Project

django-admin startproject EmployeeData

Create Django App

django-admin startapp api

Register api app in django settings install apps.

# EmployeeData > EmployeeData > settings.py
INSTALLED_APPS = [
	    'django.contrib.admin',
	    'django.contrib.auth',
	    'django.contrib.contenttypes',
	    'django.contrib.sessions',
	    'django.contrib.messages',
	    'django.contrib.staticfiles',
	    'api',
	]

Write Send Employee Data using json view

# EmployeeData > api > views.py

from django.shortcuts import render
from django.http import HttpResponse

def employee_html_view(request):
  employee_table={
    'emp-no':387001,
    'emp-name':'Bhushan Zade',
    'emp-salary': 45000,
    'emp-address': 'Nashik'
  }

response = '<h1>This is HTML response of Python Django Rest Framework </h1><h2>Employee ID : {} <br><br> Employee Name : {} <br><br> Employee Salary : {} <br><br> Employee Address : {} <br></h2>'.format(
    employee_table['emp-no'],
    employee_table['emp-name'],
    employee_table['emp-salary'],
    employee_table['emp-address'],
)

return HttpResponse(response)

Add route into urls.py file

# EmployeeData > EmployeeData > urls.py

from django.contrib import admin
from django.urls import path
from myproject1.api import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', views.employee_html_view)
]

Now migrate the app and run server.


open browser to see result and add this link to opened browser i.e. http://127.0.0.1:8000/api/

Finish.


Thank You!



0replies
Leave a reply
46
Registerd Users
88
Total Subscribers
59
Total Articles
42113
Total Views