Introduction to Django JsonResponse
JSON is a format very flexibly preferred nowadays, so support for JSON is extended across all technology formats. This is because of the easy capability to reference and parse data in JSON objects. This parsing capability offers a large extent of preference for JSON objects. So as like other platforms Django also offers support for JSON and support is offered in the means of JSON response. So when data is rendered as like the rendering for HTML page JSON objects can also be rendered. This rendering of JSON objects is depicted below.
Syntax:
from django.http import JsonResponse
JsonResponse(data,safe=TRUE/FALSE)
How JsonResponse works?
The process of how the JSON works can be explained based on how the data is received for these JSON objects. The first and major element to ensure is to import the JsonResponse class from Django. http library. This is a very critical step, only if the Django. http library shares the JsonRespose class then the JSON-based rendering can be performed. The class will make the JSON response element to be available for the remaining of the program. Next, the data for rendering needs to be formulated. The data targeted for rendering can be input from forms, it can be data being formed on random input, it can be database-based data. Wherever the data comes from it needs to be ensured that it is formulated. So the data formulation is a very critical section since this decides on how the data has to be populated and which data is involved in the process. After this comes the key part of data rendering. The data rendering is the critical section where the JSON response will be rendered. This process involves depicting the data onto the console. The URL entry for the data must also need to be placed.
Create a Django JsonResponse:
1) Changes in Models.py file: The JsonResponse charge at the same time as submitted ought to be stored and at the same time as retrieved it ought to be pulled from the database. This can be completed via the object created for the model. The way of doing this is described withinside the beneath neath given views.py section.
(models.py)
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
JsonResponse_Example_name = models.CharField(max_length=200,null=True)
JsonResponse_Example_thegai = models.CharField(max_length=200,null=True)
JsonResponse_Example_State = models.CharField(max_length=50,null=True)
JsonResponse_Example_District = models.CharField(max_length=50,null=True)
JsonResponse_Example_Address = models.TextField(null=True)
JsonResponse_Example_Phone = models.BigJsonResponse_Example_Field(null=True)
JsonResponse_Example_profession = models.CharField(max_length=200,null=True)
JsonResponse_Example_salary = models.BigJsonResponse_Example_Field(null=True)
JsonResponse_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
JsonResponse_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
JsonResponse_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
JsonResponse_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
JsonResponse_Example_Rasi = models.CharField(max_length=200,null=True)
JsonResponse_Example_Nakshatra = models.CharField(max_length=200,null=True)
JsonResponse_Example_Creator = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def _str_(self):
return self.name
2) Changes in Forms.py file:
Below are the changes associated to the forms.py file. The changes mention adding the table bride in this forms.py file. So what happens is all the fields from the table will be getting associated hereby declaring them in forms.py file.
Ex: (forms.py)
from django import forms
from .models import Bride
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Valueform(forms.ModelForm):
# Rasi = forms.ChoiceField(choices = Rasi_CHOICES)
class Meta:
model = Bride
fields = "__all__"
3) Changes in Settings.py file:
Ensure all of the values and the database connects are set nicely withinside the settings.py record in order that the undertaking may be kicked for execution flexibly.
(Settings.py):
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'render_dict_processors': [
'django.template.render_dict_processors.debug',
'django.template.render_dict_processors.request',
'django.contrib.auth.render_dict_processors.auth',
'django.contrib.messages.render_dict_processors.messages',
],
},
},
]
4) Changes in url.py file:
The Media root and document root variable need to be instantiated inside the url.py file as like below. The changes for the url.py file are mentioned below.
url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$',views.Welcome_page,name='Welcome_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
path(r'profile/<str:pk>/',views.JsonResponse_Example_page,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.JsonResponse_Example_reg_user,name='reg'),
path(r'update/<str:pk>/',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
3) Create a view for the form: The JsonResponse rate whilst submitted need to be stored and whilst retrieved it need to be pulled from the database. This can be finished thru the object created for the model. The way of doing this is described withinside the below given views.py section.
Ex: views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import NewUserForm,Valueform
from django.contrib.auth import login,authenticate,logout
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test,login_required
from django.core.paginator import Paginator
from django.http import JsonResponse
def form_view(request):
form = Valueform(request.POST or None)
if form.is_valid():
post = form.save()
post.Creator = request.user
print('Creator user stored',request.user)
post.save()
return render(request,'form.html', {"form": form})
@login_required
def JsonResponse_Example_page(request,pk):
Json_dict = {}
JsonResponse_key_variable_ = Bride.objects.get(id=pk)
JsonResponse_Example_name = JsonResponse_key_variable_.name
JsonResponse_Example_Age = Bride.objects.JsonResponse(first_name='Nalandan', last_name='Ranjan',defaults={'birthday': date(1990, 10, 9)})
JsonResponse_Example_Thegai = JsonResponse_key_variable_.thegai
JsonResponse_Example_state = JsonResponse_key_variable_.State
JsonResponse_Example_district = JsonResponse_key_variable_.District
JsonResponse_Example_Address = JsonResponse_key_variable_.Address
JsonResponse_Example_Phone = JsonResponse_key_variable_.Phone
JsonResponse_Example_Profession = JsonResponse_key_variable_.profession
JsonResponse_Example_Salary = JsonResponse_key_variable_.salary
JsonResponse_Example_UG = JsonResponse_key_variable_.Under_Graduation_Degree
JsonResponse_Example_UGC = JsonResponse_key_variable_.Under_Graduation_college
JsonResponse_Example_PG = JsonResponse_key_variable_.Post_Graduation_Degree
JsonResponse_Example_PGC = JsonResponse_key_variable_.Post_Graduation_college
JsonResponse_Example_UG = JsonResponse_key_variable_.Under_Graduation_Degree
JsonResponse_Example_UGC = JsonResponse_key_variable_.Under_Graduation_college
JsonResponse_Example_PG = JsonResponse_key_variable_.Post_Graduation_Degree
JsonResponse_Example_PGC = JsonResponse_key_variable_.Post_Graduation_college
JsonResponse_Example_Rasi = JsonResponse_key_variable_.Rasi
JsonResponse_Example_Nakshatra = JsonResponse_key_variable_.Nakshatra
Json_dict['Age'] = JsonResponse_Example_Age
Json_dict['name'] = JsonResponse_Example_name
Json_dict['thegai'] = JsonResponse_Example_Thegai
Json_dict['State'] = JsonResponse_Example_state
Json_dict['district'] = JsonResponse_Example_district
Json_dict['Address'] = JsonResponse_Example_Address
Json_dict['Phone'] = JsonResponse_Example_Phone
Json_dict['profession'] = JsonResponse_Example_Profession
Json_dict['Under_Graduation_Degree'] = JsonResponse_Example_UG
Json_dict['Under_Graduation_college'] = JsonResponse_Example_UGC
Json_dict['Post_Graduation_Degree'] = JsonResponse_Example_PG
Json_dict['Post_Graduation_college'] = JsonResponse_Example_PGC
Json_dict['Rasi'] = JsonResponse_Example_Rasi
Json_dict['Nakshatra'] = JsonResponse_Example_Nakshatra
return render(request,'Profilepage.html',Json_dict)
+def Json_Response(request):
jsondata = [{'name': 'Name of bride'},
{'Age': 'Age of Bride'},
{'thegai': 'Thegai'},
{'state': 'state of bride'},
{'district': 'bride district'},
{'address': 'address details'},
{'phone': 'phone details'},
{'UGD': 'Degree details'},
{'UGC': 'College details'},
{'PGD': 'Post Degree details'},
{'PGC': 'post College details'},
{'Rasi': 'details of rasi'},
{'Nakshatra': 'Nakshatra details'}
]
return JsonResponse(jsondata, safe=False)
Output:
Conclusion
The above-given procedure mentions the way to claim JsonResponse area combos in Django, the syntax of the identical is mentioned in conjunction with the procedure of ways the JsonResponse relationships works in Django. A stay internet site instance is likewise furnished in conjunction with snaps from the internet site. Changes to all of the Django-associated documents are mentioned above.
Recommended Articles
This is a guide to Django JsonResponse. Here we discuss the Introduction, syntax, How JsonResponse works? Examples, and code implementation. You may also have a look at the following articles to learn more –
2 Online Courses | 2 Hands-on Projects | 14+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses