Updated May 2, 2023
Introduction to Django Response
The Http response class captures the outcome of the processing of a webpage. The Http response class assigns response-oriented characteristics to a response when a returned value is cached. Special attributes and methods can capture and verify these response-oriented characteristics, similar to how the request framework operates. Each of these attributes and methods displays the corresponding value associated with the response. Specifically, these response methods and attributes are useful for verifying various information related to the response. Let’s briefly discuss these attributes and methods with suitable examples. In this topic, we will learn about Django Response.
Response Framework Attributes
Here are some of the attributes of the Django response framework:
HttpResponse attribute | Reason |
HttpResponse.content | This attribute is used to denote the content of the message |
HttpResponse.charset | A string value represents the character encoding of the response. |
HttpResponse.status_code | This represents the response status code |
HttpResponse.reason_phrase | This represents the reason phrase of the response |
HttpResponse.streaming | Mentions whether it is a streamed communication or not. |
HttpResponse.closed | When the formulated response is closed then this value is assigned as true |
Response Framework Methods
Below, we mention all the methods associated with the response framework.
Httpresponse attribute | Description |
HttpResponse.__init__(content=”, content_type=None, status=200, reason=None, charset=None) | The response object is associated with the content page and content type. |
HttpResponse.__setitem__(header, value) | The value is associated with the header name |
HttpResponse.__delitem__(header) | Deletes a specific header |
HttpResponse.__getitem__(header) | Returns a value for the specific header name |
HttpResponse.has_header(header) | It returns either True or False based on a case-insensitive check for a header with the provided name. |
HttpResponse.setdefault(header, value) | Allows to formulate a default header value |
HttpResponse.write(content) | This creates the response for a file-like object. |
HttpResponse.flush() | Allows the response object to get flushed |
HttpResponse.tell() | A file-like object will be created in the response |
HttpResponse.getvalue() | It is used to get the value of HttpResponse.content. |
HttpResponse.readable() | A stream-like object will be created in the response |
HttpResponse.seekable() | Makes the response object reachable |
Examples of Django Response
Here are the following examples mention below:
Example #1
Design the choiceField() in the forms.py with the values it needs to display and process in the choices attribute of the field.
views.py:
def email_sending(response):
email = emailform()
if response.method == 'POST':
email_id = response.POST['email']
email_subject = response.POST['email_subject']
email_message = response.POST['email_message']
mail = send_mail(email_subject,email_message,'[email protected]',[email_id],fail_silently = False)
response = HttpResponse(mail)
print("Content of the resposne: ",response.content)
print("Charecterset of the response: ",response.charset)
print("Status code of the response: ",response.status_code)
print("Reason phrase of the response: ",response.reason_phrase)
print("Reason close status: ",response.closed)
return response
return render(response, 'emailpage.html',{"email":email})
Design the webpage in the corresponding template file for this page,
Response_methods_check.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
{% load static %}
<link href="{% static 'admin/css/font.css' %}" rel="stylesheet">
<style>
body {
background-image: url("{% static 'admin/img/background.jpg' %}");
background-color: #acccbb;
}
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
font-family: "Comic Sans MS", cursive, sans-serif;
font-size: 14px;
letter-spacing: 2px;
word-spacing: 1.8px;
text-align: left;
color: #02071C;
font-weight: 200;
text-decoration: none;
font-style: normal;
font-variant: normal;
text-transform: capitalize;
}
</style>
</head>
<body>
<h1> <u> DJANGO HANDELING EMAILS </u> </h1>
<div class="myDiv" style = "max-width:470px;">
<form method = 'POST' ">
{{ email.as_p }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submit" style="text-align:center">
</form>
</div>
</body>
</html>
Output:
,
Example #2
Here the response values from a file upload page is been verified
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform,fileform,emailform,responsecheckform
from django.core.exceptions import ViewDoesNotExist
from django.contrib.auth.models import User
from django.core.files.storage import FileSystemStorage
from django.contrib import messages
from django.core.mail import send_mail,EmailMessage
import responses
def file_upload(response):
file = fileform()
print(" File Values in File Dictionary:", response.FILES)
if response.method == 'POST' and response.FILES['Uploaded_File']:
uploaded_file = response.FILES['Uploaded_File']
fs = FileSystemStorage()
filename = fs.save(uploaded_file.name, uploaded_file)
uploaded_File_Size = 'Size of Uploaded file: ' + str(uploaded_file.size)
content_type_of_uploaded_file = 'Content type of uploaded file: ' + str(uploaded_file.content_type)
uploaded_file_name = 'Name of Uploaded file: ' + str(uploaded_file.name)
uploaded_file_url = fs.url(filename)
print("uploaded file url",uploaded_file_url)
messages.success(response, '!!! File upload successful !!!')
messages.success(response,uploaded_File_Size)
messages.success(response,uploaded_file_name)
messages.success(response,content_type_of_uploaded_file)
response = HttpResponse(filename)
print("Content of the resposne: ",response.content)
print("Charecterset of the response: ",response.charset)
print("Status code of the response: ",response.status_code)
print("Reason phrase of the response: ",response.reason_phrase)
print("Reason close status: ",response.closed)
return render(response, 'filehandeling.html', {"file":file})
return render(response, 'filehandeling.html',{"file":file})
Html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
{% load static %}
<link href="{% static 'admin/css/font.css' %}" rel="stylesheet">
<style>
body {
background-image: url("{% static 'admin/img/background.jpg' %}");
background-color: #acccbb;
}
</style>
</head>
<body>
<h1> <u> FILE UPLOAD HANDELING IN DJANGO </u> </h1>
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<div style = "max-width:470px;">
<form method = 'POST' enctype="multipart/form-data">
{{ file.as_p }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submit">
</form>
</div>
</body>
</html>
Output:
Example #3
The response values generated from a form page are captured and verified.
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform,fileform,emailform,responsecheckform
from django.core.exceptions import ViewDoesNotExist
from django.contrib.auth.models import User
from django.core.files.storage import FileSystemStorage
from django.contrib import messages
from django.core.mail import send_mail,EmailMessage
import responses
def formView(response_iter):
form = Valueform()
if response_iter.method == "POST":
value = Valueform(response_iter.POST)
if value.is_valid():
first_name = value.cleaned_data['first_name']
response = HttpResponse(first_name)
print("Content of the resposne: ",response.content)
print("Charecterset of the response: ",response.charset)
print("Status code of the response: ",response.status_code)
print("Reason phrase of the response: ",response.reason_phrase)
print("Reason close status: ",response.closed)
if response_iter.session.has_key(first_name):
print(response_iter.session.items())
return render(response_iter, 'Session.html' )
else:
response_iter.session[first_name] = first_name
return render(response_iter, 'Form_Handeling.html', {"form":form}))
Html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
{% load static %}
<link href="{% static 'admin/css/base.css' %}" rel="stylesheet">
<style>
body {
background-image: url("{% static 'admin/img/background1.jpg' %}");
background-color: #acccbb;
}
</style>
</head>
<body>
<h1> <u> FORMS HANDELING IN DJANGO </u> </h1>
<div style = "max-width:470px;">
<form method = 'GET'>
{{ emailform.as_p }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submit">
</form>
</div>
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
</body>
</html>
Output:
Conclusion
From the above-provided descriptions and examples, the key information related to the Httpresponse framework can be understood.
Recommended Articles
We hope that this EDUCBA information on “Django Response” was beneficial to you. You can view EDUCBA’s recommended articles for more information.