Interacting with Django Front and Rear Ends
Django, a Python web framework, provides a robust way to interact between the front end and rear end of a web application. In this section, we will explore how to submit data from the front end to the rear end using forms and Ajax requests.
Using Django Templates
Django comes with a built-in templating engine that allows us to render dynamic content. We can use templates to submit data from the front end to the rear end using forms.
Form Example
The following is an example of a form in a Django template that submits data to the rear end:
<!-- /Template/demo/demo.html -->
{% if result == 1 %}
<p>On successful insertion</p>
{% elif result == 2 %}
<p>Insert failed</p>
{% endif %}
<form class="layui-form" method="post" action="{% url 'demo:type_add' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="type_name" required autocomplete="off" class="layui-input">
<input type="text" name="type_sort" required autocomplete="off" class="layui-input">
<input type="submit" value="Submit">
</form>
Back-end Data Transfer
To transfer data from the rear end to the template file, we use a rendering function. The following is an example of a view function that handles the form submission:
# /Demo/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import DemoType
def type_add(request):
# Form data
type_name = request.POST['type_name']
type_sort = request.POST['type_sort']
# Database operation
result = DemoType.objects.create(type_name=type_name, type_sort=type_sort)
if result:
return render(request, 'demo/demo.html', {'result': 1})
else:
# return HttpResponse('Insert failed!')
return render(request, 'demo/demo.html', {'result': 2})
Using Ajax
Ajax is a technique for sending asynchronous requests to the rear end and modifying the displayed page dynamically. The following is an example of how to send an Ajax request to the rear end:
// Front-end function
function demo(demo_id) {
$.ajax({
url: 'url',
type: 'POST',
headers: {
"X-CSRFToken": '{{csrf_token}}'
},
data: {
demo_id: demo_id
},
dataType: 'json',
success: function(e) {
// Get data from the rear end and modify the page
console.log(e);
}
});
}
// Rear-end function
def demo(request):
# Get demo_id from the request
demo_id = request.GET.get('demo_id', 0)
# POST request
params = json.loads(request.body)
demo_id = params.get('demo_id', 0)
user_id = request.session.get('user_id', 0)
return_param = {}
try:
# Database operation
demo.objects.update_or_create(users_id=user_id, demo_id=demo_id, status=1)
return_param['status'] = 200
return_param['msg'] = 'success'
except Exception as e:
return_param['status'] = 500
return_param['msg'] = 'fail'
return JsonResponse(BaseResponse(code=SUCCESS_CODE, msg='success', data=[]).__dict__)
Standardized Response Format
To facilitate standardized responses from the rear end, we can create a new file in the same folder and define a class in the settings.py file:
# settings.py
SUCCESS_CODE, FAIL_CODE, PARMS_CODE = 200, 400, 404
class BaseResponse:
def __init__(self, **kwargs):
self.status_code = kwargs.get('code', 0)
self.message = kwargs.get('msg', '')
self.data = kwargs.get('data', [])
By using this standardized response format, we can easily modify the front end to handle different responses from the rear end.
Note: The code snippets provided are for illustration purposes only and may need to be modified to fit your specific use case.