Introduction to Django jsonfield
JSON has now become a very common datatype across software platforms. The flexibility of JSON fields helps to easily fetch and depict the data, and processing can also be performed in a sophisticated manner with JSON fields. These JSON fields are used even in outputs of large applications like amazon textract for fetching the output. These are among the critical needs of JSON fields. So these fields are largely used in today’s market, and Django also produces them for forms and models. Almost all the database backends supported by Django can have these jsonfields in them. The syntax and the process of getting these JSON fields added to the model are discussed below. The parameter of setting the fields as all allows the model to inherit all the fields used in the model described. In this topic, we are going to learn about Django jsonfield.
Syntax:
Jsonfield = models.JSONField()
The above-given syntax allows to create of a model field sophisticatedly. The models class is inherited, and the JSONField()method is used within the models class. This JSONField() method can be associated with arguments such as Null and Null based values and etc. The Created class is mapped onto a variable. From there on, the mapped variable will be a responsible field for this Json field model.
Create a Django jsonfield
Below are the steps to create a Django jsonfield:
1. Changes in Models.py file
The models.py file is generated with a JSON field declared in it along with the other fields present. We can notice the model has a large variety of fields. This model schema will be associated with a form on top of it. The form will be integrated with it all the fields of this corresponding model through a JSONFIELD import. This is how the import process works for the models. Very importantly, the JSON field is allocated with a nullable value which allows all the non-value records for this field to hold a default value of Null. Removing this argument from the field may throw an error on the migrations process.
Ex: (models.py)
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Bride(models.Model):
name = models.CharField(max_length=200,null=True)
age = models.IntegerField(null=True)
thegai = models.CharField(max_length=200,null=True)
State = models.CharField(max_length=50,null=True)
District = models.CharField(max_length=50,null=True)
Address = models.TextField(null=True)
Phone = models.BigIntegerField(null=True)
profession = models.CharField(max_length=200,null=True)
salary = models.BigIntegerField(null=True)
Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Under_Graduation_college = models.CharField(max_length=400,null=True)
Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Post_Graduation_college = models.CharField(max_length=400,null=True)
Rasi = models.CharField(max_length=200,null=True)
Nakshatra = models.CharField(max_length=200,null=True)
Jsonfield = models. JSONField(null=True)
def __str__(self):
return self.name
2. Changes in Forms.py file
The forms.py file is created with the model from the models.py imported here. In these examples case, the form will be imported with the model details, and then from there on, the model will be allocated here. The model allocation will be taking place within the class Meta: statement. For example, here model = Bride will allow the Bride class to be associated here. The parameter of setting the fields as all allows the model to inherits all the fields used in the model described.
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. Create a view for the form
A Django view needs to be created to make the middleware for the form with the JSON field listed in it be rendered. Here the form is saved when the submit button is clicked. We can notice from the below code of views that the views.py first imports render from the shortcuts of the Django library. This renders import will be very useful in getting the html file rendered onto the browser. Then the HTTP response is imported. The Value form will be instantiated here in the views method. The instantiation will be performed on a variable called form. On top of the instantiation, the value of the form returned is verified for validity. If the value of the form is valid, then the save process of the form will be performed. The save process will take place with the form.save() method. Then the currently logged-in user details will be fetched and stored on the form. This is how the form storage will take place. After the form is successfully stored, it will be rendered onto the browser with a render method.
Ex: (views.py)
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform
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})
4. Formulate an HTML file for displaying the form
An HTML record desires to be created withinside the template listing for showing the shape; right here, the record is template tagged with the use of the under the tag,
{{ form.as_p }}
right here, “as_p” is used for higher designing of the shape elements. The line is used for testifying the inner safety verification achieved through Django.
Form.html:
<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<title>form</title>
{% load static %}
<link rel="stylesheet" href="{% static 'admin/css/Formpage.css' %}" media="screen">
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home! </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
</div>
</nav>
<div class="body">
<br>
{% block content %}
<form method="POST" class='formarea'>
<div class='formdiv'>
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class='button' value="submit">
</div>
</form>
{% endblock content %}
</div>
<script>
function form1() {
window.location.href = "http://127.0.0.1:8000/form";
}
function redirect1() {
window.location.href = "http://127.0.0.1:8000/Mainpage";
}
function redirect2() {
window.location.href = "http://127.0.0.1:8000/";
}
</script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"> </script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Output:
Conclusion
From the above-mentioned article, we can understand the process of creating a JSON field in Django, and additionally, we can furtherly verify how this field is mapped onto a form and form the form setup how this specific field gets processed in the view associated to the model. Additionally, the HTML code linked to these forms are also produced, and from there on, the site placed on port 8000 is brought live in a browser.